module.ts 14 KB

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