module.ts 11 KB

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