module.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 '../../../core/time_series2';
  8. import {MetricsPanelCtrl} from '../../../features/panel/panel';
  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 = 'public/app/plugins/panel/singlestat/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', '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. this.dataHandler(snapshotData);
  73. }
  74. dataHandler(results) {
  75. this.series = _.map(results.data, this.seriesHandler.bind(this));
  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. render() {
  134. var data: any = {};
  135. this.setValues(data);
  136. data.thresholds = this.panel.thresholds.split(',').map(function(strVale) {
  137. return Number(strVale.trim());
  138. });
  139. data.colorMap = this.panel.colors;
  140. this.data = data;
  141. this.broadcastRender();
  142. }
  143. setValues(data) {
  144. data.flotpairs = [];
  145. if (this.series.length > 1) {
  146. this.inspector.error = new Error();
  147. this.inspector.error.message = 'Multiple Series Error';
  148. this.inspector.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 this.inspector.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.value) {
  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, $panelContainer;
  205. var firstRender = true;
  206. scope.$on('render', function() {
  207. if (firstRender) {
  208. var inner = elem.find('.singlestat-panel');
  209. if (inner.length) {
  210. elem = inner;
  211. $panelContainer = elem.parents('.panel-container');
  212. firstRender = false;
  213. hookupDrilldownLinkTooltip();
  214. } else {
  215. return;
  216. }
  217. }
  218. render();
  219. ctrl.renderingCompleted();
  220. });
  221. function setElementHeight() {
  222. try {
  223. var height = scope.height || panel.height || ctrl.row.height;
  224. if (_.isString(height)) {
  225. height = parseInt(height.replace('px', ''), 10);
  226. }
  227. height -= 5; // padding
  228. height -= panel.title ? 24 : 9; // subtract panel title bar
  229. elem.css('height', height + 'px');
  230. return true;
  231. } catch (e) { // IE throws errors sometimes
  232. return false;
  233. }
  234. }
  235. function applyColoringThresholds(value, valueString) {
  236. if (!panel.colorValue) {
  237. return valueString;
  238. }
  239. var color = getColorForValue(data, value);
  240. if (color) {
  241. return '<span style="color:' + color + '">'+ valueString + '</span>';
  242. }
  243. return valueString;
  244. }
  245. function getSpan(className, fontSize, value) {
  246. value = templateSrv.replace(value);
  247. return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
  248. value + '</span>';
  249. }
  250. function getBigValueHtml() {
  251. var body = '<div class="singlestat-panel-value-container">';
  252. if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.prefix); }
  253. var value = applyColoringThresholds(data.valueRounded, data.valueFormated);
  254. body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
  255. if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
  256. body += '</div>';
  257. return body;
  258. }
  259. function addSparkline() {
  260. var width = elem.width() + 20;
  261. var height = elem.height() || 100;
  262. var plotCanvas = $('<div></div>');
  263. var plotCss: any = {};
  264. plotCss.position = 'absolute';
  265. if (panel.sparkline.full) {
  266. plotCss.bottom = '5px';
  267. plotCss.left = '-5px';
  268. plotCss.width = (width - 10) + 'px';
  269. var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
  270. plotCss.height = (height - dynamicHeightMargin) + 'px';
  271. } else {
  272. plotCss.bottom = "0px";
  273. plotCss.left = "-5px";
  274. plotCss.width = (width - 10) + 'px';
  275. plotCss.height = Math.floor(height * 0.25) + "px";
  276. }
  277. plotCanvas.css(plotCss);
  278. var options = {
  279. legend: { show: false },
  280. series: {
  281. lines: {
  282. show: true,
  283. fill: 1,
  284. lineWidth: 1,
  285. fillColor: panel.sparkline.fillColor,
  286. },
  287. },
  288. yaxes: { show: false },
  289. xaxis: {
  290. show: false,
  291. mode: "time",
  292. min: ctrl.range.from.valueOf(),
  293. max: ctrl.range.to.valueOf(),
  294. },
  295. grid: { hoverable: false, show: false },
  296. };
  297. elem.append(plotCanvas);
  298. var plotSeries = {
  299. data: data.flotpairs,
  300. color: panel.sparkline.lineColor
  301. };
  302. $.plot(plotCanvas, [plotSeries], options);
  303. }
  304. function render() {
  305. if (!ctrl.data) { return; }
  306. data = ctrl.data;
  307. setElementHeight();
  308. var body = getBigValueHtml();
  309. if (panel.colorBackground && !isNaN(data.valueRounded)) {
  310. var color = getColorForValue(data, data.valueRounded);
  311. if (color) {
  312. $panelContainer.css('background-color', color);
  313. if (scope.fullscreen) {
  314. elem.css('background-color', color);
  315. } else {
  316. elem.css('background-color', '');
  317. }
  318. }
  319. } else {
  320. $panelContainer.css('background-color', '');
  321. elem.css('background-color', '');
  322. }
  323. elem.html(body);
  324. if (panel.sparkline.show) {
  325. addSparkline();
  326. }
  327. elem.toggleClass('pointer', panel.links.length > 0);
  328. if (panel.links.length > 0) {
  329. linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], panel.scopedVars);
  330. } else {
  331. linkInfo = null;
  332. }
  333. }
  334. function hookupDrilldownLinkTooltip() {
  335. // drilldown link tooltip
  336. var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
  337. elem.mouseleave(function() {
  338. if (panel.links.length === 0) { return;}
  339. drilldownTooltip.detach();
  340. });
  341. elem.click(function(evt) {
  342. if (!linkInfo) { return; }
  343. // ignore title clicks in title
  344. if ($(evt).parents('.panel-header').length > 0) { return; }
  345. if (linkInfo.target === '_blank') {
  346. var redirectWindow = window.open(linkInfo.href, '_blank');
  347. redirectWindow.location;
  348. return;
  349. }
  350. if (linkInfo.href.indexOf('http') === 0) {
  351. window.location.href = linkInfo.href;
  352. } else {
  353. $timeout(function() {
  354. $location.url(linkInfo.href);
  355. });
  356. }
  357. drilldownTooltip.detach();
  358. });
  359. elem.mousemove(function(e) {
  360. if (!linkInfo) { return;}
  361. drilldownTooltip.text('click to go to: ' + linkInfo.title);
  362. drilldownTooltip.place_tt(e.pageX+20, e.pageY-15);
  363. });
  364. }
  365. }
  366. }
  367. function getColorForValue(data, value) {
  368. for (var i = data.thresholds.length; i > 0; i--) {
  369. if (value >= data.thresholds[i-1]) {
  370. return data.colorMap[i];
  371. }
  372. }
  373. return _.first(data.colorMap);
  374. }
  375. export {
  376. SingleStatCtrl,
  377. SingleStatCtrl as PanelCtrl,
  378. getColorForValue
  379. };