module.ts 12 KB

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