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('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. // Add $seriesName variable for using in prefix or postfix
  173. data.scopedVars = {
  174. seriesName: {
  175. value: this.series[0].label
  176. }
  177. };
  178. }
  179. // check value to text mappings if its enabled
  180. if (this.panel.mappingType === 1) {
  181. for (var i = 0; i < this.panel.valueMaps.length; i++) {
  182. var map = this.panel.valueMaps[i];
  183. // special null case
  184. if (map.value === 'null') {
  185. if (data.value === null || data.value === void 0) {
  186. data.valueFormated = map.text;
  187. return;
  188. }
  189. continue;
  190. }
  191. // value/number to text mapping
  192. var value = parseFloat(map.value);
  193. if (value === data.valueRounded) {
  194. data.valueFormated = map.text;
  195. return;
  196. }
  197. }
  198. } else if (this.panel.mappingType === 2) {
  199. for (var i = 0; i < this.panel.rangeMaps.length; i++) {
  200. var map = this.panel.rangeMaps[i];
  201. // special null case
  202. if (map.from === 'null' && map.to === 'null') {
  203. if (data.value === null || data.value === void 0) {
  204. data.valueFormated = map.text;
  205. return;
  206. }
  207. continue;
  208. }
  209. // value/number to range mapping
  210. var from = parseFloat(map.from);
  211. var to = parseFloat(map.to);
  212. if (to >= data.valueRounded && from <= data.valueRounded) {
  213. data.valueFormated = map.text;
  214. return;
  215. }
  216. }
  217. }
  218. if (data.value === null || data.value === void 0) {
  219. data.valueFormated = "no value";
  220. }
  221. };
  222. removeValueMap(map) {
  223. var index = _.indexOf(this.panel.valueMaps, map);
  224. this.panel.valueMaps.splice(index, 1);
  225. this.render();
  226. };
  227. addValueMap() {
  228. this.panel.valueMaps.push({value: '', op: '=', text: '' });
  229. }
  230. removeRangeMap(rangeMap) {
  231. var index = _.indexOf(this.panel.rangeMaps, rangeMap);
  232. this.panel.rangeMaps.splice(index, 1);
  233. this.render();
  234. };
  235. addRangeMap() {
  236. this.panel.rangeMaps.push({from: '', to: '', text: ''});
  237. }
  238. link(scope, elem, attrs, ctrl) {
  239. var $location = this.$location;
  240. var linkSrv = this.linkSrv;
  241. var $timeout = this.$timeout;
  242. var panel = ctrl.panel;
  243. var templateSrv = this.templateSrv;
  244. var data, linkInfo;
  245. var $panelContainer = elem.find('.panel-container');
  246. elem = elem.find('.singlestat-panel');
  247. function setElementHeight() {
  248. elem.css('height', ctrl.height + 'px');
  249. }
  250. function applyColoringThresholds(value, valueString) {
  251. if (!panel.colorValue) {
  252. return valueString;
  253. }
  254. var color = getColorForValue(data, value);
  255. if (color) {
  256. return '<span style="color:' + color + '">'+ valueString + '</span>';
  257. }
  258. return valueString;
  259. }
  260. function getSpan(className, fontSize, value) {
  261. value = templateSrv.replace(value, data.scopedVars);
  262. return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
  263. value + '</span>';
  264. }
  265. function getBigValueHtml() {
  266. var body = '<div class="singlestat-panel-value-container">';
  267. if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.prefix); }
  268. var value = applyColoringThresholds(data.value, data.valueFormated);
  269. body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
  270. if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
  271. body += '</div>';
  272. return body;
  273. }
  274. function getValueText() {
  275. var result = panel.prefix ? panel.prefix : '';
  276. result += data.valueFormated;
  277. result += panel.postfix ? panel.postfix : '';
  278. return result;
  279. }
  280. function addGauge() {
  281. var width = elem.width();
  282. var height = elem.height();
  283. ctrl.invalidGaugeRange = false;
  284. if (panel.gauge.minValue > panel.gauge.maxValue) {
  285. ctrl.invalidGaugeRange = true;
  286. return;
  287. }
  288. var plotCanvas = $('<div></div>');
  289. var plotCss = {
  290. top: '10px',
  291. margin: 'auto',
  292. position: 'relative',
  293. height: (height * 0.9) + 'px',
  294. width: width + 'px'
  295. };
  296. plotCanvas.css(plotCss);
  297. var thresholds = [];
  298. for (var i = 0; i < data.thresholds.length; i++) {
  299. thresholds.push({
  300. value: data.thresholds[i],
  301. color: data.colorMap[i]
  302. });
  303. }
  304. thresholds.push({
  305. value: panel.gauge.maxValue,
  306. color: data.colorMap[data.colorMap.length - 1]
  307. });
  308. var bgColor = config.bootData.user.lightTheme
  309. ? 'rgb(230,230,230)'
  310. : 'rgb(38,38,38)';
  311. var fontScale = parseInt(panel.valueFontSize) / 100;
  312. var dimension = Math.min(width, height);
  313. var fontSize = Math.min(dimension/5, 100) * fontScale;
  314. var gaugeWidth = Math.min(dimension/6, 60);
  315. var thresholdMarkersWidth = gaugeWidth/5;
  316. var options = {
  317. series: {
  318. gauges: {
  319. gauge: {
  320. min: panel.gauge.minValue,
  321. max: panel.gauge.maxValue,
  322. background: { color: bgColor },
  323. border: { color: null },
  324. shadow: { show: false },
  325. width: gaugeWidth,
  326. },
  327. frame: { show: false },
  328. label: { show: false },
  329. layout: { margin: 0, thresholdWidth: 0 },
  330. cell: { border: { width: 0 } },
  331. threshold: {
  332. values: thresholds,
  333. label: {
  334. show: panel.gauge.thresholdLabels,
  335. margin: 8,
  336. font: { size: 18 }
  337. },
  338. show: panel.gauge.thresholdMarkers,
  339. width: thresholdMarkersWidth,
  340. },
  341. value: {
  342. color: panel.colorValue ? getColorForValue(data, data.valueRounded) : null,
  343. formatter: function() { return getValueText(); },
  344. font: { size: fontSize, family: 'Helvetica Neue", Helvetica, Arial, sans-serif' }
  345. },
  346. show: true
  347. }
  348. }
  349. };
  350. elem.append(plotCanvas);
  351. var plotSeries = {
  352. data: [[0, data.valueRounded]]
  353. };
  354. $.plot(plotCanvas, [plotSeries], options);
  355. }
  356. function addSparkline() {
  357. var width = elem.width() + 20;
  358. if (width < 30) {
  359. // element has not gotten it's width yet
  360. // delay sparkline render
  361. setTimeout(addSparkline, 30);
  362. return;
  363. }
  364. var height = ctrl.height;
  365. var plotCanvas = $('<div></div>');
  366. var plotCss: any = {};
  367. plotCss.position = 'absolute';
  368. if (panel.sparkline.full) {
  369. plotCss.bottom = '5px';
  370. plotCss.left = '-5px';
  371. plotCss.width = (width - 10) + 'px';
  372. var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
  373. plotCss.height = (height - dynamicHeightMargin) + 'px';
  374. } else {
  375. plotCss.bottom = "0px";
  376. plotCss.left = "-5px";
  377. plotCss.width = (width - 10) + 'px';
  378. plotCss.height = Math.floor(height * 0.25) + "px";
  379. }
  380. plotCanvas.css(plotCss);
  381. var options = {
  382. legend: { show: false },
  383. series: {
  384. lines: {
  385. show: true,
  386. fill: 1,
  387. lineWidth: 1,
  388. fillColor: panel.sparkline.fillColor,
  389. },
  390. },
  391. yaxes: { show: false },
  392. xaxis: {
  393. show: false,
  394. mode: "time",
  395. min: ctrl.range.from.valueOf(),
  396. max: ctrl.range.to.valueOf(),
  397. },
  398. grid: { hoverable: false, show: false },
  399. };
  400. elem.append(plotCanvas);
  401. var plotSeries = {
  402. data: data.flotpairs,
  403. color: panel.sparkline.lineColor
  404. };
  405. $.plot(plotCanvas, [plotSeries], options);
  406. }
  407. function render() {
  408. if (!ctrl.data) { return; }
  409. data = ctrl.data;
  410. // get thresholds
  411. data.thresholds = panel.thresholds.split(',').map(function(strVale) {
  412. return Number(strVale.trim());
  413. });
  414. data.colorMap = panel.colors;
  415. setElementHeight();
  416. var body = panel.gauge.show ? '' : getBigValueHtml();
  417. if (panel.colorBackground && !isNaN(data.valueRounded)) {
  418. var color = getColorForValue(data, data.valueRounded);
  419. if (color) {
  420. $panelContainer.css('background-color', color);
  421. if (scope.fullscreen) {
  422. elem.css('background-color', color);
  423. } else {
  424. elem.css('background-color', '');
  425. }
  426. }
  427. } else {
  428. $panelContainer.css('background-color', '');
  429. elem.css('background-color', '');
  430. }
  431. elem.html(body);
  432. if (panel.sparkline.show) {
  433. addSparkline();
  434. }
  435. if (panel.gauge.show) {
  436. addGauge();
  437. }
  438. elem.toggleClass('pointer', panel.links.length > 0);
  439. if (panel.links.length > 0) {
  440. linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], panel.scopedVars);
  441. } else {
  442. linkInfo = null;
  443. }
  444. }
  445. function hookupDrilldownLinkTooltip() {
  446. // drilldown link tooltip
  447. var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
  448. elem.mouseleave(function() {
  449. if (panel.links.length === 0) { return;}
  450. drilldownTooltip.detach();
  451. });
  452. elem.click(function(evt) {
  453. if (!linkInfo) { return; }
  454. // ignore title clicks in title
  455. if ($(evt).parents('.panel-header').length > 0) { return; }
  456. if (linkInfo.target === '_blank') {
  457. var redirectWindow = window.open(linkInfo.href, '_blank');
  458. redirectWindow.location;
  459. return;
  460. }
  461. if (linkInfo.href.indexOf('http') === 0) {
  462. window.location.href = linkInfo.href;
  463. } else {
  464. $timeout(function() {
  465. $location.url(linkInfo.href);
  466. });
  467. }
  468. drilldownTooltip.detach();
  469. });
  470. elem.mousemove(function(e) {
  471. if (!linkInfo) { return;}
  472. drilldownTooltip.text('click to go to: ' + linkInfo.title);
  473. drilldownTooltip.place_tt(e.pageX+20, e.pageY-15);
  474. });
  475. }
  476. hookupDrilldownLinkTooltip();
  477. this.events.on('render', function() {
  478. render();
  479. ctrl.renderingCompleted();
  480. });
  481. }
  482. }
  483. function getColorForValue(data, value) {
  484. for (var i = data.thresholds.length; i > 0; i--) {
  485. if (value >= data.thresholds[i-1]) {
  486. return data.colorMap[i];
  487. }
  488. }
  489. return _.first(data.colorMap);
  490. }
  491. export {
  492. SingleStatCtrl,
  493. SingleStatCtrl as PanelCtrl,
  494. getColorForValue
  495. };