module.ts 16 KB

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