module.ts 18 KB

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