module.ts 20 KB

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