module.ts 14 KB

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