module.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import $ from 'jquery';
  5. import 'jquery.flot';
  6. import 'jquery.flot.gauge';
  7. import kbn from 'app/core/utils/kbn';
  8. import config from 'app/core/config';
  9. import TimeSeries from 'app/core/time_series2';
  10. import {MetricsPanelCtrl} from 'app/plugins/sdk';
  11. class SingleStatCtrl extends MetricsPanelCtrl {
  12. static templateUrl = 'module.html';
  13. series: any[];
  14. data: any;
  15. fontSizes: any[];
  16. unitFormats: any[];
  17. invalidGaugeRange: boolean;
  18. // Set and populate defaults
  19. panelDefaults = {
  20. links: [],
  21. datasource: null,
  22. maxDataPoints: 100,
  23. interval: null,
  24. targets: [{}],
  25. cacheTimeout: null,
  26. format: 'none',
  27. prefix: '',
  28. postfix: '',
  29. nullText: null,
  30. valueMaps: [
  31. { value: 'null', op: '=', text: 'N/A' }
  32. ],
  33. nullPointMode: 'connected',
  34. valueName: 'avg',
  35. prefixFontSize: '50%',
  36. valueFontSize: '80%',
  37. postfixFontSize: '50%',
  38. thresholds: '',
  39. colorBackground: false,
  40. colorValue: false,
  41. colors: ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
  42. sparkline: {
  43. show: false,
  44. full: false,
  45. lineColor: 'rgb(31, 120, 193)',
  46. fillColor: 'rgba(31, 118, 189, 0.18)',
  47. },
  48. gauge: {
  49. show: false,
  50. minValue: 0,
  51. maxValue: 100,
  52. thresholdMarkers: true,
  53. thresholdLabels: false
  54. }
  55. };
  56. /** @ngInject */
  57. constructor($scope, $injector, private $location, private linkSrv) {
  58. super($scope, $injector);
  59. _.defaults(this.panel, this.panelDefaults);
  60. this.events.on('data-received', this.onDataReceived.bind(this));
  61. this.events.on('data-error', this.onDataError.bind(this));
  62. this.events.on('data-snapshot-load', this.onDataReceived.bind(this));
  63. this.events.on('init-edit-mode', this.onInitEditMode.bind(this));
  64. }
  65. onInitEditMode() {
  66. this.fontSizes = ['20%', '30%','50%','70%','80%','100%', '110%', '120%', '150%', '170%', '200%'];
  67. this.addEditorTab('Options', 'public/app/plugins/panel/singlestat/editor.html', 2);
  68. this.unitFormats = kbn.getUnitFormats();
  69. }
  70. setUnitFormat(subItem) {
  71. this.panel.format = subItem.value;
  72. this.render();
  73. }
  74. onDataError(err) {
  75. this.onDataReceived([]);
  76. }
  77. onDataReceived(dataList) {
  78. this.series = dataList.map(this.seriesHandler.bind(this));
  79. var data: any = {};
  80. this.setValues(data);
  81. this.data = data;
  82. this.render();
  83. }
  84. seriesHandler(seriesData) {
  85. var series = new TimeSeries({
  86. datapoints: seriesData.datapoints,
  87. alias: seriesData.target,
  88. });
  89. series.flotpairs = series.getFlotPairs(this.panel.nullPointMode);
  90. return series;
  91. }
  92. setColoring(options) {
  93. if (options.background) {
  94. this.panel.colorValue = false;
  95. this.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
  96. } else {
  97. this.panel.colorBackground = false;
  98. this.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
  99. }
  100. this.render();
  101. }
  102. invertColorOrder() {
  103. var tmp = this.panel.colors[0];
  104. this.panel.colors[0] = this.panel.colors[2];
  105. this.panel.colors[2] = tmp;
  106. this.render();
  107. }
  108. getDecimalsForValue(value) {
  109. if (_.isNumber(this.panel.decimals)) {
  110. return {decimals: this.panel.decimals, scaledDecimals: null};
  111. }
  112. var delta = value / 2;
  113. var dec = -Math.floor(Math.log(delta) / Math.LN10);
  114. var magn = Math.pow(10, -dec),
  115. norm = delta / magn, // norm is between 1.0 and 10.0
  116. size;
  117. if (norm < 1.5) {
  118. size = 1;
  119. } else if (norm < 3) {
  120. size = 2;
  121. // special case for 2.5, requires an extra decimal
  122. if (norm > 2.25) {
  123. size = 2.5;
  124. ++dec;
  125. }
  126. } else if (norm < 7.5) {
  127. size = 5;
  128. } else {
  129. size = 10;
  130. }
  131. size *= magn;
  132. // reduce starting decimals if not needed
  133. if (Math.floor(value) === value) { dec = 0; }
  134. var result: any = {};
  135. result.decimals = Math.max(0, dec);
  136. result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;
  137. return result;
  138. }
  139. setValues(data) {
  140. data.flotpairs = [];
  141. if (this.series.length > 1) {
  142. var error: any = new Error();
  143. error.message = 'Multiple Series Error';
  144. error.data = 'Metric query returns ' + this.series.length +
  145. ' series. Single Stat Panel expects a single series.\n\nResponse:\n'+JSON.stringify(this.series);
  146. throw error;
  147. }
  148. if (this.series && this.series.length > 0) {
  149. var lastPoint = _.last(this.series[0].datapoints);
  150. var lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;
  151. if (_.isString(lastValue)) {
  152. data.value = 0;
  153. data.valueFormated = lastValue;
  154. data.valueRounded = 0;
  155. } else {
  156. data.value = this.series[0].stats[this.panel.valueName];
  157. data.flotpairs = this.series[0].flotpairs;
  158. var decimalInfo = this.getDecimalsForValue(data.value);
  159. var formatFunc = kbn.valueFormats[this.panel.format];
  160. data.valueFormated = formatFunc(data.value, decimalInfo.decimals, decimalInfo.scaledDecimals);
  161. data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
  162. }
  163. }
  164. // check value to text mappings
  165. for (var i = 0; i < this.panel.valueMaps.length; i++) {
  166. var map = this.panel.valueMaps[i];
  167. // special null case
  168. if (map.value === 'null') {
  169. if (data.value === null || data.value === void 0) {
  170. data.valueFormated = map.text;
  171. return;
  172. }
  173. continue;
  174. }
  175. // value/number to text mapping
  176. var value = parseFloat(map.value);
  177. if (value === data.valueRounded) {
  178. data.valueFormated = map.text;
  179. return;
  180. }
  181. }
  182. if (data.value === null || data.value === void 0) {
  183. data.valueFormated = "no value";
  184. }
  185. };
  186. removeValueMap(map) {
  187. var index = _.indexOf(this.panel.valueMaps, map);
  188. this.panel.valueMaps.splice(index, 1);
  189. this.render();
  190. };
  191. addValueMap() {
  192. this.panel.valueMaps.push({value: '', op: '=', text: '' });
  193. }
  194. link(scope, elem, attrs, ctrl) {
  195. var $location = this.$location;
  196. var linkSrv = this.linkSrv;
  197. var $timeout = this.$timeout;
  198. var panel = ctrl.panel;
  199. var templateSrv = this.templateSrv;
  200. var data, linkInfo;
  201. var width, height;
  202. var $panelContainer = elem.find('.panel-container');
  203. elem = elem.find('.singlestat-panel');
  204. function setElementHeight() {
  205. width = elem.width();
  206. height = elem.height();
  207. elem.css('height', ctrl.height + 'px');
  208. }
  209. function applyColoringThresholds(value, valueString) {
  210. if (!panel.colorValue) {
  211. return valueString;
  212. }
  213. var color = getColorForValue(data, value);
  214. if (color) {
  215. return '<span style="color:' + color + '">'+ valueString + '</span>';
  216. }
  217. return valueString;
  218. }
  219. function getSpan(className, fontSize, value) {
  220. value = templateSrv.replace(value);
  221. return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
  222. value + '</span>';
  223. }
  224. function getBigValueHtml() {
  225. var body = '<div class="singlestat-panel-value-container">';
  226. if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.prefix); }
  227. var value = applyColoringThresholds(data.value, data.valueFormated);
  228. body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
  229. if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
  230. body += '</div>';
  231. return body;
  232. }
  233. function getValueText() {
  234. var result = panel.prefix ? panel.prefix : '';
  235. result += data.valueFormated;
  236. result += panel.postfix ? panel.postfix : '';
  237. return result;
  238. }
  239. function addGauge() {
  240. ctrl.invalidGaugeRange = false;
  241. if (panel.gauge.minValue > panel.gauge.maxValue) {
  242. ctrl.invalidGaugeRange = true;
  243. return;
  244. }
  245. var plotCanvas = $('<div></div>');
  246. var plotCss = {
  247. top: '10px',
  248. margin: 'auto',
  249. position: 'relative',
  250. height: (height * 0.9) + 'px',
  251. width: width + 'px'
  252. };
  253. plotCanvas.css(plotCss);
  254. var thresholds = [];
  255. for (var i = 0; i < data.thresholds.length; i++) {
  256. thresholds.push({
  257. value: data.thresholds[i],
  258. color: data.colorMap[i]
  259. });
  260. }
  261. thresholds.push({
  262. value: panel.gauge.maxValue,
  263. color: data.colorMap[data.colorMap.length - 1]
  264. });
  265. var bgColor = config.bootData.user.lightTheme
  266. ? 'rgb(230,230,230)'
  267. : 'rgb(38,38,38)';
  268. var fontScale = parseInt(panel.valueFontSize) / 100;
  269. var dimension = Math.min(width, height);
  270. var fontSize = Math.min(dimension/5, 100) * fontScale;
  271. var gaugeWidth = Math.min(dimension/6, 60);
  272. var thresholdMarkersWidth = gaugeWidth/5;
  273. var options = {
  274. series: {
  275. gauges: {
  276. gauge: {
  277. min: panel.gauge.minValue,
  278. max: panel.gauge.maxValue,
  279. background: { color: bgColor },
  280. border: { color: null },
  281. shadow: { show: false },
  282. width: gaugeWidth,
  283. },
  284. frame: { show: false },
  285. label: { show: false },
  286. layout: { margin: 0, thresholdWidth: 0 },
  287. cell: { border: { width: 0 } },
  288. threshold: {
  289. values: thresholds,
  290. label: {
  291. show: panel.gauge.thresholdLabels,
  292. margin: 8,
  293. font: { size: 18 }
  294. },
  295. show: panel.gauge.thresholdMarkers,
  296. width: thresholdMarkersWidth,
  297. },
  298. value: {
  299. color: panel.colorValue ? getColorForValue(data, data.valueRounded) : null,
  300. formatter: function() { return getValueText(); },
  301. font: { size: fontSize, family: 'Helvetica Neue", Helvetica, Arial, sans-serif' }
  302. },
  303. show: true
  304. }
  305. }
  306. };
  307. elem.append(plotCanvas);
  308. var plotSeries = {
  309. data: [[0, data.valueRounded]]
  310. };
  311. $.plot(plotCanvas, [plotSeries], options);
  312. }
  313. function addSparkline() {
  314. var width = elem.width() + 20;
  315. if (width < 30) {
  316. // element has not gotten it's width yet
  317. // delay sparkline render
  318. setTimeout(addSparkline, 30);
  319. return;
  320. }
  321. var height = ctrl.height;
  322. var plotCanvas = $('<div></div>');
  323. var plotCss: any = {};
  324. plotCss.position = 'absolute';
  325. if (panel.sparkline.full) {
  326. plotCss.bottom = '5px';
  327. plotCss.left = '-5px';
  328. plotCss.width = (width - 10) + 'px';
  329. var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
  330. plotCss.height = (height - dynamicHeightMargin) + 'px';
  331. } else {
  332. plotCss.bottom = "0px";
  333. plotCss.left = "-5px";
  334. plotCss.width = (width - 10) + 'px';
  335. plotCss.height = Math.floor(height * 0.25) + "px";
  336. }
  337. plotCanvas.css(plotCss);
  338. var options = {
  339. legend: { show: false },
  340. series: {
  341. lines: {
  342. show: true,
  343. fill: 1,
  344. lineWidth: 1,
  345. fillColor: panel.sparkline.fillColor,
  346. },
  347. },
  348. yaxes: { show: false },
  349. xaxis: {
  350. show: false,
  351. mode: "time",
  352. min: ctrl.range.from.valueOf(),
  353. max: ctrl.range.to.valueOf(),
  354. },
  355. grid: { hoverable: false, show: false },
  356. };
  357. elem.append(plotCanvas);
  358. var plotSeries = {
  359. data: data.flotpairs,
  360. color: panel.sparkline.lineColor
  361. };
  362. $.plot(plotCanvas, [plotSeries], options);
  363. }
  364. function render() {
  365. if (!ctrl.data) { return; }
  366. data = ctrl.data;
  367. // get thresholds
  368. data.thresholds = panel.thresholds.split(',').map(function(strVale) {
  369. return Number(strVale.trim());
  370. });
  371. data.colorMap = panel.colors;
  372. setElementHeight();
  373. var body = panel.gauge.show ? '' : getBigValueHtml();
  374. if (panel.colorBackground && !isNaN(data.valueRounded)) {
  375. var color = getColorForValue(data, data.valueRounded);
  376. if (color) {
  377. $panelContainer.css('background-color', color);
  378. if (scope.fullscreen) {
  379. elem.css('background-color', color);
  380. } else {
  381. elem.css('background-color', '');
  382. }
  383. }
  384. } else {
  385. $panelContainer.css('background-color', '');
  386. elem.css('background-color', '');
  387. }
  388. elem.html(body);
  389. if (panel.sparkline.show) {
  390. addSparkline();
  391. }
  392. if (panel.gauge.show) {
  393. addGauge();
  394. }
  395. elem.toggleClass('pointer', panel.links.length > 0);
  396. if (panel.links.length > 0) {
  397. linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], panel.scopedVars);
  398. } else {
  399. linkInfo = null;
  400. }
  401. }
  402. function hookupDrilldownLinkTooltip() {
  403. // drilldown link tooltip
  404. var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
  405. elem.mouseleave(function() {
  406. if (panel.links.length === 0) { return;}
  407. drilldownTooltip.detach();
  408. });
  409. elem.click(function(evt) {
  410. if (!linkInfo) { return; }
  411. // ignore title clicks in title
  412. if ($(evt).parents('.panel-header').length > 0) { return; }
  413. if (linkInfo.target === '_blank') {
  414. var redirectWindow = window.open(linkInfo.href, '_blank');
  415. redirectWindow.location;
  416. return;
  417. }
  418. if (linkInfo.href.indexOf('http') === 0) {
  419. window.location.href = linkInfo.href;
  420. } else {
  421. $timeout(function() {
  422. $location.url(linkInfo.href);
  423. });
  424. }
  425. drilldownTooltip.detach();
  426. });
  427. elem.mousemove(function(e) {
  428. if (!linkInfo) { return;}
  429. drilldownTooltip.text('click to go to: ' + linkInfo.title);
  430. drilldownTooltip.place_tt(e.pageX+20, e.pageY-15);
  431. });
  432. }
  433. hookupDrilldownLinkTooltip();
  434. this.events.on('render', function() {
  435. render();
  436. ctrl.renderingCompleted();
  437. });
  438. }
  439. }
  440. function getColorForValue(data, value) {
  441. for (var i = data.thresholds.length; i > 0; i--) {
  442. if (value >= data.thresholds[i-1]) {
  443. return data.colorMap[i];
  444. }
  445. }
  446. return _.first(data.colorMap);
  447. }
  448. export {
  449. SingleStatCtrl,
  450. SingleStatCtrl as PanelCtrl,
  451. getColorForValue
  452. };