module.ts 14 KB

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