module.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. }
  157. setColoring(options) {
  158. if (options.background) {
  159. this.panel.colorValue = false;
  160. this.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
  161. } else {
  162. this.panel.colorBackground = false;
  163. this.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
  164. }
  165. this.render();
  166. }
  167. invertColorOrder() {
  168. var tmp = this.panel.colors[0];
  169. this.panel.colors[0] = this.panel.colors[2];
  170. this.panel.colors[2] = tmp;
  171. this.render();
  172. }
  173. getDecimalsForValue(value) {
  174. if (_.isNumber(this.panel.decimals)) {
  175. return {decimals: this.panel.decimals, scaledDecimals: null};
  176. }
  177. var delta = value / 2;
  178. var dec = -Math.floor(Math.log(delta) / Math.LN10);
  179. var magn = Math.pow(10, -dec),
  180. norm = delta / magn, // norm is between 1.0 and 10.0
  181. size;
  182. if (norm < 1.5) {
  183. size = 1;
  184. } else if (norm < 3) {
  185. size = 2;
  186. // special case for 2.5, requires an extra decimal
  187. if (norm > 2.25) {
  188. size = 2.5;
  189. ++dec;
  190. }
  191. } else if (norm < 7.5) {
  192. size = 5;
  193. } else {
  194. size = 10;
  195. }
  196. size *= magn;
  197. // reduce starting decimals if not needed
  198. if (Math.floor(value) === value) { dec = 0; }
  199. var result: any = {};
  200. result.decimals = Math.max(0, dec);
  201. result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;
  202. return result;
  203. }
  204. setValues(data) {
  205. data.flotpairs = [];
  206. if (this.series.length > 1) {
  207. var error: any = new Error();
  208. error.message = 'Multiple Series Error';
  209. error.data = 'Metric query returns ' + this.series.length +
  210. ' series. Single Stat Panel expects a single series.\n\nResponse:\n'+JSON.stringify(this.series);
  211. throw error;
  212. }
  213. if (this.series && this.series.length > 0) {
  214. var lastPoint = _.last(this.series[0].datapoints);
  215. var lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;
  216. if (this.panel.valueName === 'name') {
  217. data.value = 0;
  218. data.valueRounded = 0;
  219. data.valueFormatted = this.series[0].alias;
  220. } else if (_.isString(lastValue)) {
  221. data.value = 0;
  222. data.valueFormatted = _.escape(lastValue);
  223. data.valueRounded = 0;
  224. } else {
  225. data.value = this.series[0].stats[this.panel.valueName];
  226. data.flotpairs = this.series[0].flotpairs;
  227. var decimalInfo = this.getDecimalsForValue(data.value);
  228. var formatFunc = kbn.valueFormats[this.panel.format];
  229. data.valueFormatted = formatFunc(data.value, decimalInfo.decimals, decimalInfo.scaledDecimals);
  230. data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
  231. }
  232. // Add $__name variable for using in prefix or postfix
  233. data.scopedVars = _.extend({}, this.panel.scopedVars);
  234. data.scopedVars["__name"] = {value: this.series[0].label};
  235. }
  236. // check value to text mappings if its enabled
  237. if (this.panel.mappingType === 1) {
  238. for (let i = 0; i < this.panel.valueMaps.length; i++) {
  239. let map = this.panel.valueMaps[i];
  240. // special null case
  241. if (map.value === 'null') {
  242. if (data.value === null || data.value === void 0) {
  243. data.valueFormatted = map.text;
  244. return;
  245. }
  246. continue;
  247. }
  248. // value/number to text mapping
  249. var value = parseFloat(map.value);
  250. if (value === data.valueRounded) {
  251. data.valueFormatted = map.text;
  252. return;
  253. }
  254. }
  255. } else if (this.panel.mappingType === 2) {
  256. for (let i = 0; i < this.panel.rangeMaps.length; i++) {
  257. let map = this.panel.rangeMaps[i];
  258. // special null case
  259. if (map.from === 'null' && map.to === 'null') {
  260. if (data.value === null || data.value === void 0) {
  261. data.valueFormatted = map.text;
  262. return;
  263. }
  264. continue;
  265. }
  266. // value/number to range mapping
  267. var from = parseFloat(map.from);
  268. var to = parseFloat(map.to);
  269. if (to >= data.valueRounded && from <= data.valueRounded) {
  270. data.valueFormatted = map.text;
  271. return;
  272. }
  273. }
  274. }
  275. if (data.value === null || data.value === void 0) {
  276. data.valueFormatted = "no value";
  277. }
  278. }
  279. removeValueMap(map) {
  280. var index = _.indexOf(this.panel.valueMaps, map);
  281. this.panel.valueMaps.splice(index, 1);
  282. this.render();
  283. }
  284. addValueMap() {
  285. this.panel.valueMaps.push({value: '', op: '=', text: '' });
  286. }
  287. removeRangeMap(rangeMap) {
  288. var index = _.indexOf(this.panel.rangeMaps, rangeMap);
  289. this.panel.rangeMaps.splice(index, 1);
  290. this.render();
  291. }
  292. addRangeMap() {
  293. this.panel.rangeMaps.push({from: '', to: '', text: ''});
  294. }
  295. link(scope, elem, attrs, ctrl) {
  296. var $location = this.$location;
  297. var linkSrv = this.linkSrv;
  298. var $timeout = this.$timeout;
  299. var panel = ctrl.panel;
  300. var templateSrv = this.templateSrv;
  301. var data, linkInfo;
  302. var $panelContainer = elem.find('.panel-container');
  303. elem = elem.find('.singlestat-panel');
  304. function setElementHeight() {
  305. elem.css('height', ctrl.height + 'px');
  306. }
  307. function applyColoringThresholds(value, valueString) {
  308. if (!panel.colorValue) {
  309. return valueString;
  310. }
  311. var color = getColorForValue(data, value);
  312. if (color) {
  313. return '<span style="color:' + color + '">'+ valueString + '</span>';
  314. }
  315. return valueString;
  316. }
  317. function getSpan(className, fontSize, value) {
  318. value = templateSrv.replace(value, data.scopedVars);
  319. return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
  320. value + '</span>';
  321. }
  322. function getBigValueHtml() {
  323. var body = '<div class="singlestat-panel-value-container">';
  324. if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.prefix); }
  325. var value = applyColoringThresholds(data.value, data.valueFormatted);
  326. body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
  327. if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
  328. body += '</div>';
  329. return body;
  330. }
  331. function getValueText() {
  332. var result = panel.prefix ? panel.prefix : '';
  333. result += data.valueFormatted;
  334. result += panel.postfix ? panel.postfix : '';
  335. return result;
  336. }
  337. function addGauge() {
  338. var width = elem.width();
  339. var height = elem.height();
  340. ctrl.invalidGaugeRange = false;
  341. if (panel.gauge.minValue > panel.gauge.maxValue) {
  342. ctrl.invalidGaugeRange = true;
  343. return;
  344. }
  345. var plotCanvas = $('<div></div>');
  346. var plotCss = {
  347. top: '10px',
  348. margin: 'auto',
  349. position: 'relative',
  350. height: (height * 0.9) + 'px',
  351. width: width + 'px'
  352. };
  353. plotCanvas.css(plotCss);
  354. var thresholds = [];
  355. for (var i = 0; i < data.thresholds.length; i++) {
  356. thresholds.push({
  357. value: data.thresholds[i],
  358. color: data.colorMap[i]
  359. });
  360. }
  361. thresholds.push({
  362. value: panel.gauge.maxValue,
  363. color: data.colorMap[data.colorMap.length - 1]
  364. });
  365. var bgColor = config.bootData.user.lightTheme
  366. ? 'rgb(230,230,230)'
  367. : 'rgb(38,38,38)';
  368. var fontScale = parseInt(panel.valueFontSize) / 100;
  369. var dimension = Math.min(width, height);
  370. var fontSize = Math.min(dimension/5, 100) * fontScale;
  371. var gaugeWidth = Math.min(dimension/6, 60);
  372. var thresholdMarkersWidth = gaugeWidth/5;
  373. var options = {
  374. series: {
  375. gauges: {
  376. gauge: {
  377. min: panel.gauge.minValue,
  378. max: panel.gauge.maxValue,
  379. background: { color: bgColor },
  380. border: { color: null },
  381. shadow: { show: false },
  382. width: gaugeWidth,
  383. },
  384. frame: { show: false },
  385. label: { show: false },
  386. layout: { margin: 0, thresholdWidth: 0 },
  387. cell: { border: { width: 0 } },
  388. threshold: {
  389. values: thresholds,
  390. label: {
  391. show: panel.gauge.thresholdLabels,
  392. margin: 8,
  393. font: { size: 18 }
  394. },
  395. show: panel.gauge.thresholdMarkers,
  396. width: thresholdMarkersWidth,
  397. },
  398. value: {
  399. color: panel.colorValue ? getColorForValue(data, data.valueRounded) : null,
  400. formatter: function() { return getValueText(); },
  401. font: { size: fontSize, family: '"Helvetica Neue", Helvetica, Arial, sans-serif' }
  402. },
  403. show: true
  404. }
  405. }
  406. };
  407. elem.append(plotCanvas);
  408. var plotSeries = {
  409. data: [[0, data.valueRounded]]
  410. };
  411. $.plot(plotCanvas, [plotSeries], options);
  412. }
  413. function addSparkline() {
  414. var width = elem.width() + 20;
  415. if (width < 30) {
  416. // element has not gotten it's width yet
  417. // delay sparkline render
  418. setTimeout(addSparkline, 30);
  419. return;
  420. }
  421. var height = ctrl.height;
  422. var plotCanvas = $('<div></div>');
  423. var plotCss: any = {};
  424. plotCss.position = 'absolute';
  425. if (panel.sparkline.full) {
  426. plotCss.bottom = '5px';
  427. plotCss.left = '-5px';
  428. plotCss.width = (width - 10) + 'px';
  429. var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
  430. plotCss.height = (height - dynamicHeightMargin) + 'px';
  431. } else {
  432. plotCss.bottom = "0px";
  433. plotCss.left = "-5px";
  434. plotCss.width = (width - 10) + 'px';
  435. plotCss.height = Math.floor(height * 0.25) + "px";
  436. }
  437. plotCanvas.css(plotCss);
  438. var options = {
  439. legend: { show: false },
  440. series: {
  441. lines: {
  442. show: true,
  443. fill: 1,
  444. lineWidth: 1,
  445. fillColor: panel.sparkline.fillColor,
  446. },
  447. },
  448. yaxes: { show: false },
  449. xaxis: {
  450. show: false,
  451. mode: "time",
  452. min: ctrl.range.from.valueOf(),
  453. max: ctrl.range.to.valueOf(),
  454. },
  455. grid: { hoverable: false, show: false },
  456. };
  457. elem.append(plotCanvas);
  458. var plotSeries = {
  459. data: data.flotpairs,
  460. color: panel.sparkline.lineColor
  461. };
  462. $.plot(plotCanvas, [plotSeries], options);
  463. }
  464. function render() {
  465. if (!ctrl.data) { return; }
  466. data = ctrl.data;
  467. // get thresholds
  468. data.thresholds = panel.thresholds.split(',').map(function(strVale) {
  469. return Number(strVale.trim());
  470. });
  471. data.colorMap = panel.colors;
  472. setElementHeight();
  473. var body = panel.gauge.show ? '' : getBigValueHtml();
  474. if (panel.colorBackground && !isNaN(data.valueRounded)) {
  475. var color = getColorForValue(data, data.valueRounded);
  476. if (color) {
  477. $panelContainer.css('background-color', color);
  478. if (scope.fullscreen) {
  479. elem.css('background-color', color);
  480. } else {
  481. elem.css('background-color', '');
  482. }
  483. }
  484. } else {
  485. $panelContainer.css('background-color', '');
  486. elem.css('background-color', '');
  487. }
  488. elem.html(body);
  489. if (panel.sparkline.show) {
  490. addSparkline();
  491. }
  492. if (panel.gauge.show) {
  493. addGauge();
  494. }
  495. elem.toggleClass('pointer', panel.links.length > 0);
  496. if (panel.links.length > 0) {
  497. linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], data.scopedVars);
  498. } else {
  499. linkInfo = null;
  500. }
  501. }
  502. function hookupDrilldownLinkTooltip() {
  503. // drilldown link tooltip
  504. var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
  505. elem.mouseleave(function() {
  506. if (panel.links.length === 0) { return;}
  507. $timeout(function() {
  508. drilldownTooltip.detach();
  509. });
  510. });
  511. elem.click(function(evt) {
  512. if (!linkInfo) { return; }
  513. // ignore title clicks in title
  514. if ($(evt).parents('.panel-header').length > 0) { return; }
  515. if (linkInfo.target === '_blank') {
  516. var redirectWindow = window.open(linkInfo.href, '_blank');
  517. redirectWindow.location;
  518. return;
  519. }
  520. if (linkInfo.href.indexOf('http') === 0) {
  521. window.location.href = linkInfo.href;
  522. } else {
  523. $timeout(function() {
  524. $location.url(linkInfo.href);
  525. });
  526. }
  527. drilldownTooltip.detach();
  528. });
  529. elem.mousemove(function(e) {
  530. if (!linkInfo) { return;}
  531. drilldownTooltip.text('click to go to: ' + linkInfo.title);
  532. drilldownTooltip.place_tt(e.pageX, e.pageY-50);
  533. });
  534. }
  535. hookupDrilldownLinkTooltip();
  536. this.events.on('render', function() {
  537. render();
  538. ctrl.renderingCompleted();
  539. });
  540. }
  541. }
  542. function getColorForValue(data, value) {
  543. for (var i = data.thresholds.length; i > 0; i--) {
  544. if (value >= data.thresholds[i-1]) {
  545. return data.colorMap[i];
  546. }
  547. }
  548. return _.first(data.colorMap);
  549. }
  550. export {
  551. SingleStatCtrl,
  552. SingleStatCtrl as PanelCtrl,
  553. getColorForValue
  554. };