module.ts 16 KB

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