module.ts 15 KB

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