module.ts 18 KB

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