module.ts 14 KB

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