module.ts 11 KB

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