module.ts 16 KB

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