module.ts 19 KB

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