module.ts 16 KB

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