graph.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'moment',
  5. 'lodash',
  6. 'app/core/utils/kbn',
  7. './graph_tooltip',
  8. './alert_handle',
  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, AlertHandle) {
  19. 'use strict';
  20. var module = angular.module('grafana.directives');
  21. var labelWidthCache = {};
  22. var panelWidthCache = {};
  23. // systemjs export
  24. var AlertHandleManager = AlertHandle.AlertHandleManager;
  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 alertHandles;
  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 (alertHandles) {
  145. alertHandles.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 (!alertHandles) {
  166. elem.css('margin-right', '220px');
  167. alertHandles = new AlertHandleManager(ctrl);
  168. }
  169. } else if (alertHandles) {
  170. elem.css('margin-right', '0');
  171. alertHandles.cleanUp();
  172. alertHandles = 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. var crit = panel.alert.critical;
  293. var warn = panel.alert.warn;
  294. var critEdge = Infinity;
  295. var warnEdge = crit.level;
  296. if (_.isNumber(crit.level)) {
  297. if (crit.op === '<') {
  298. critEdge = -Infinity;
  299. }
  300. // fill
  301. options.grid.markings.push({
  302. yaxis: {from: crit.level, to: critEdge},
  303. color: 'rgba(234, 112, 112, 0.10)',
  304. });
  305. // line
  306. options.grid.markings.push({
  307. yaxis: {from: crit.level, to: crit.level},
  308. color: '#ed2e18'
  309. });
  310. }
  311. if (_.isNumber(warn.level)) {
  312. // if (warn.op === '<') {
  313. // }
  314. // fill
  315. options.grid.markings.push({
  316. yaxis: {from: warn.level, to: warnEdge},
  317. color: 'rgba(216, 200, 27, 0.10)',
  318. });
  319. // line
  320. options.grid.markings.push({
  321. yaxis: {from: warn.level, to: warn.level},
  322. color: '#F79520'
  323. });
  324. }
  325. return;
  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. if (_.isNumber(panel.grid.threshold2)) {
  334. var limit2;
  335. if (panel.grid.thresholdLine) {
  336. limit2 = panel.grid.threshold2;
  337. } else {
  338. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  339. }
  340. options.grid.markings.push({
  341. yaxis: { from: panel.grid.threshold2, to: limit2 },
  342. color: panel.grid.threshold2Color
  343. });
  344. }
  345. }
  346. }
  347. function addAnnotations(options) {
  348. if(!annotations || annotations.length === 0) {
  349. return;
  350. }
  351. var types = {};
  352. _.each(annotations, function(event) {
  353. if (!types[event.annotation.name]) {
  354. types[event.annotation.name] = {
  355. color: event.annotation.iconColor,
  356. position: 'BOTTOM',
  357. markerSize: 5,
  358. };
  359. }
  360. });
  361. options.events = {
  362. levels: _.keys(types).length + 1,
  363. data: annotations,
  364. types: types,
  365. };
  366. }
  367. function configureAxisOptions(data, options) {
  368. var defaults = {
  369. position: 'left',
  370. show: panel.yaxes[0].show,
  371. min: panel.yaxes[0].min,
  372. index: 1,
  373. logBase: panel.yaxes[0].logBase || 1,
  374. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  375. };
  376. options.yaxes.push(defaults);
  377. if (_.findWhere(data, {yaxis: 2})) {
  378. var secondY = _.clone(defaults);
  379. secondY.index = 2,
  380. secondY.show = panel.yaxes[1].show;
  381. secondY.logBase = panel.yaxes[1].logBase || 1,
  382. secondY.position = 'right';
  383. secondY.min = panel.yaxes[1].min;
  384. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  385. options.yaxes.push(secondY);
  386. applyLogScale(options.yaxes[1], data);
  387. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  388. }
  389. applyLogScale(options.yaxes[0], data);
  390. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  391. }
  392. function applyLogScale(axis, data) {
  393. if (axis.logBase === 1) {
  394. return;
  395. }
  396. var series, i;
  397. var max = axis.max;
  398. if (max === null) {
  399. for (i = 0; i < data.length; i++) {
  400. series = data[i];
  401. if (series.yaxis === axis.index) {
  402. if (max < series.stats.max) {
  403. max = series.stats.max;
  404. }
  405. }
  406. }
  407. if (max === void 0) {
  408. max = Number.MAX_VALUE;
  409. }
  410. }
  411. axis.min = axis.min !== null ? axis.min : 0;
  412. axis.ticks = [0, 1];
  413. var nextTick = 1;
  414. while (true) {
  415. nextTick = nextTick * axis.logBase;
  416. axis.ticks.push(nextTick);
  417. if (nextTick > max) {
  418. break;
  419. }
  420. }
  421. if (axis.logBase === 10) {
  422. axis.transform = function(v) { return Math.log(v+0.1); };
  423. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  424. } else {
  425. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  426. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  427. }
  428. }
  429. function configureAxisMode(axis, format) {
  430. axis.tickFormatter = function(val, axis) {
  431. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  432. };
  433. }
  434. function time_format(ticks, min, max) {
  435. if (min && max && ticks) {
  436. var range = max - min;
  437. var secPerTick = (range/ticks) / 1000;
  438. var oneDay = 86400000;
  439. var oneYear = 31536000000;
  440. if (secPerTick <= 45) {
  441. return "%H:%M:%S";
  442. }
  443. if (secPerTick <= 7200 || range <= oneDay) {
  444. return "%H:%M";
  445. }
  446. if (secPerTick <= 80000) {
  447. return "%m/%d %H:%M";
  448. }
  449. if (secPerTick <= 2419200 || range <= oneYear) {
  450. return "%m/%d";
  451. }
  452. return "%Y-%m";
  453. }
  454. return "%H:%M";
  455. }
  456. function render_panel_as_graphite_png(url) {
  457. url += '&width=' + panelWidth;
  458. url += '&height=' + elem.css('height').replace('px', '');
  459. url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground
  460. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  461. url += panel.stack ? '&areaMode=stacked' : '';
  462. url += panel.fill !== 0 ? ('&areaAlpha=' + (panel.fill/10).toFixed(1)) : '';
  463. url += panel.linewidth !== 0 ? '&lineWidth=' + panel.linewidth : '';
  464. url += panel.legend.show ? '&hideLegend=false' : '&hideLegend=true';
  465. if (panel.yaxes && panel.yaxes.length > 0) {
  466. var showYaxis = false;
  467. for(var i = 0; panel.yaxes.length > i; i++) {
  468. if (panel.yaxes[i].show) {
  469. url += (panel.yaxes[i].min !== null && panel.yaxes[i].min !== undefined) ? '&yMin=' + panel.yaxes[i].min : '';
  470. url += (panel.yaxes[i].max !== null && panel.yaxes[i].max !== undefined) ? '&yMax=' + panel.yaxes[i].max : '';
  471. showYaxis = true;
  472. break;
  473. }
  474. }
  475. url += showYaxis ? '' : '&hideYAxis=true';
  476. }
  477. url += panel.xaxis.show ? '' : '&hideAxes=true';
  478. switch(panel.yaxes[0].format) {
  479. case 'bytes':
  480. url += '&yUnitSystem=binary';
  481. break;
  482. case 'bits':
  483. url += '&yUnitSystem=binary';
  484. break;
  485. case 'bps':
  486. url += '&yUnitSystem=si';
  487. break;
  488. case 'pps':
  489. url += '&yUnitSystem=si';
  490. break;
  491. case 'Bps':
  492. url += '&yUnitSystem=si';
  493. break;
  494. case 'short':
  495. url += '&yUnitSystem=si';
  496. break;
  497. case 'joule':
  498. url += '&yUnitSystem=si';
  499. break;
  500. case 'watt':
  501. url += '&yUnitSystem=si';
  502. break;
  503. case 'ev':
  504. url += '&yUnitSystem=si';
  505. break;
  506. case 'none':
  507. url += '&yUnitSystem=none';
  508. break;
  509. }
  510. switch(panel.nullPointMode) {
  511. case 'connected':
  512. url += '&lineMode=connected';
  513. break;
  514. case 'null':
  515. break; // graphite default lineMode
  516. case 'null as zero':
  517. url += "&drawNullAsZero=true";
  518. break;
  519. }
  520. url += panel.steppedLine ? '&lineMode=staircase' : '';
  521. elem.html('<img src="' + url + '"></img>');
  522. }
  523. new GraphTooltip(elem, dashboard, scope, function() {
  524. return sortedSeries;
  525. });
  526. elem.bind("plotselected", function (event, ranges) {
  527. scope.$apply(function() {
  528. timeSrv.setTime({
  529. from : moment.utc(ranges.xaxis.from),
  530. to : moment.utc(ranges.xaxis.to),
  531. });
  532. });
  533. });
  534. }
  535. };
  536. });
  537. });