module.ts 16 KB

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