module.ts 19 KB

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