module.ts 14 KB

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