module.ts 15 KB

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