module.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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/panel/panellinks/link_srv';
  6. import { getDecimalsForValue } from '@grafana/ui';
  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. import { GrafanaThemeType, getValueFormat, getColorFromHexRgbOrName, isTableData } from '@grafana/ui';
  12. const BASE_FONT_SIZE = 38;
  13. class SingleStatCtrl extends MetricsPanelCtrl {
  14. static templateUrl = 'module.html';
  15. dataType = 'timeseries';
  16. series: any[];
  17. data: any;
  18. fontSizes: any[];
  19. unitFormats: any[];
  20. invalidGaugeRange: boolean;
  21. panel: any;
  22. events: any;
  23. valueNameOptions: any[] = [
  24. { value: 'min', text: 'Min' },
  25. { value: 'max', text: 'Max' },
  26. { value: 'avg', text: 'Average' },
  27. { value: 'current', text: 'Current' },
  28. { value: 'total', text: 'Total' },
  29. { value: 'name', text: 'Name' },
  30. { value: 'first', text: 'First' },
  31. { value: 'delta', text: 'Delta' },
  32. { value: 'diff', text: 'Difference' },
  33. { value: 'range', text: 'Range' },
  34. { value: 'last_time', text: 'Time of last point' },
  35. ];
  36. tableColumnOptions: any;
  37. // Set and populate defaults
  38. panelDefaults = {
  39. links: [],
  40. datasource: null,
  41. maxDataPoints: 100,
  42. interval: null,
  43. targets: [{}],
  44. cacheTimeout: null,
  45. format: 'none',
  46. prefix: '',
  47. postfix: '',
  48. nullText: null,
  49. valueMaps: [{ value: 'null', op: '=', text: 'N/A' }],
  50. mappingTypes: [{ name: 'value to text', value: 1 }, { name: 'range to text', value: 2 }],
  51. rangeMaps: [{ from: 'null', to: 'null', text: 'N/A' }],
  52. mappingType: 1,
  53. nullPointMode: 'connected',
  54. valueName: 'avg',
  55. prefixFontSize: '50%',
  56. valueFontSize: '80%',
  57. postfixFontSize: '50%',
  58. thresholds: '',
  59. colorBackground: false,
  60. colorValue: false,
  61. colors: ['#299c46', 'rgba(237, 129, 40, 0.89)', '#d44a3a'],
  62. sparkline: {
  63. show: false,
  64. full: false,
  65. ymin: null,
  66. ymax: null,
  67. lineColor: 'rgb(31, 120, 193)',
  68. fillColor: 'rgba(31, 118, 189, 0.18)',
  69. },
  70. gauge: {
  71. show: false,
  72. minValue: 0,
  73. maxValue: 100,
  74. thresholdMarkers: true,
  75. thresholdLabels: false,
  76. },
  77. tableColumn: '',
  78. };
  79. /** @ngInject */
  80. constructor($scope, $injector, private linkSrv, private $sanitize) {
  81. super($scope, $injector);
  82. _.defaults(this.panel, this.panelDefaults);
  83. this.events.on('data-received', this.onDataReceived.bind(this));
  84. this.events.on('data-error', this.onDataError.bind(this));
  85. this.events.on('data-snapshot-load', this.onDataReceived.bind(this));
  86. this.events.on('init-edit-mode', this.onInitEditMode.bind(this));
  87. this.onSparklineColorChange = this.onSparklineColorChange.bind(this);
  88. this.onSparklineFillChange = this.onSparklineFillChange.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. scopedVars: _.extend({}, this.panel.scopedVars),
  106. };
  107. if (dataList.length > 0 && isTableData(dataList[0])) {
  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. const 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 (tableData.columns.length === 1) {
  149. this.panel.tableColumn = tableData.columns[0].text;
  150. } else {
  151. this.panel.tableColumn = _.find(tableData.columns, col => {
  152. return col.type !== 'time';
  153. }).text;
  154. }
  155. }
  156. setTableValues(tableData, data) {
  157. if (!tableData || tableData.length === 0) {
  158. return;
  159. }
  160. if (tableData[0].length === 0 || tableData[0][0][this.panel.tableColumn] === undefined) {
  161. return;
  162. }
  163. const datapoint = tableData[0][0];
  164. data.value = datapoint[this.panel.tableColumn];
  165. if (_.isString(data.value)) {
  166. data.valueFormatted = _.escape(data.value);
  167. data.value = 0;
  168. data.valueRounded = 0;
  169. } else {
  170. const decimalInfo = getDecimalsForValue(data.value, this.panel.decimals);
  171. const formatFunc = getValueFormat(this.panel.format);
  172. data.valueFormatted = formatFunc(
  173. datapoint[this.panel.tableColumn],
  174. decimalInfo.decimals,
  175. decimalInfo.scaledDecimals
  176. );
  177. data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
  178. }
  179. this.setValueMapping(data);
  180. }
  181. canModifyText() {
  182. return !this.panel.gauge.show;
  183. }
  184. setColoring(options) {
  185. if (options.background) {
  186. this.panel.colorValue = false;
  187. this.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
  188. } else {
  189. this.panel.colorBackground = false;
  190. this.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
  191. }
  192. this.render();
  193. }
  194. invertColorOrder() {
  195. const tmp = this.panel.colors[0];
  196. this.panel.colors[0] = this.panel.colors[2];
  197. this.panel.colors[2] = tmp;
  198. this.render();
  199. }
  200. onColorChange(panelColorIndex) {
  201. return color => {
  202. this.panel.colors[panelColorIndex] = color;
  203. this.render();
  204. };
  205. }
  206. onSparklineColorChange(newColor) {
  207. this.panel.sparkline.lineColor = newColor;
  208. this.render();
  209. }
  210. onSparklineFillChange(newColor) {
  211. this.panel.sparkline.fillColor = newColor;
  212. this.render();
  213. }
  214. setValues(data) {
  215. data.flotpairs = [];
  216. if (this.series.length > 1) {
  217. const error: any = new Error();
  218. error.message = 'Multiple Series Error';
  219. error.data =
  220. 'Metric query returns ' +
  221. this.series.length +
  222. ' series. Single Stat Panel expects a single series.\n\nResponse:\n' +
  223. JSON.stringify(this.series);
  224. throw error;
  225. }
  226. if (this.series && this.series.length > 0) {
  227. const lastPoint = _.last(this.series[0].datapoints);
  228. const lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;
  229. const formatFunc = getValueFormat(this.panel.format);
  230. if (this.panel.valueName === 'name') {
  231. data.value = 0;
  232. data.valueRounded = 0;
  233. data.valueFormatted = this.series[0].alias;
  234. } else if (_.isString(lastValue)) {
  235. data.value = 0;
  236. data.valueFormatted = _.escape(lastValue);
  237. data.valueRounded = 0;
  238. } else if (this.panel.valueName === 'last_time') {
  239. data.value = lastPoint[1];
  240. data.valueRounded = data.value;
  241. data.valueFormatted = formatFunc(data.value, 0, 0, this.dashboard.isTimezoneUtc());
  242. } else {
  243. data.value = this.series[0].stats[this.panel.valueName];
  244. data.flotpairs = this.series[0].flotpairs;
  245. const decimalInfo = getDecimalsForValue(data.value, this.panel.decimals);
  246. data.valueFormatted = formatFunc(
  247. data.value,
  248. decimalInfo.decimals,
  249. decimalInfo.scaledDecimals,
  250. this.dashboard.isTimezoneUtc()
  251. );
  252. data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
  253. }
  254. // Add $__name variable for using in prefix or postfix
  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. const 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. const 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. const 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. const from = parseFloat(map.from);
  292. const 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. const 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. const 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. const $location = this.$location;
  321. const linkSrv = this.linkSrv;
  322. const $timeout = this.$timeout;
  323. const $sanitize = this.$sanitize;
  324. const panel = ctrl.panel;
  325. const templateSrv = this.templateSrv;
  326. let data, linkInfo;
  327. const $panelContainer = elem.find('.panel-container');
  328. elem = elem.find('.singlestat-panel');
  329. function applyColoringThresholds(valueString) {
  330. const color = getColorForValue(data, data.value);
  331. if (color) {
  332. return '<span style="color:' + color + '">' + valueString + '</span>';
  333. }
  334. return valueString;
  335. }
  336. function getSpan(className, fontSizePercent, applyColoring, value) {
  337. value = $sanitize(templateSrv.replace(value, data.scopedVars));
  338. value = applyColoring ? applyColoringThresholds(value) : value;
  339. const pixelSize = (parseInt(fontSizePercent, 10) / 100) * BASE_FONT_SIZE;
  340. return '<span class="' + className + '" style="font-size:' + pixelSize + 'px">' + value + '</span>';
  341. }
  342. function getBigValueHtml() {
  343. let body = '<div class="singlestat-panel-value-container">';
  344. if (panel.prefix) {
  345. body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.colorPrefix, panel.prefix);
  346. }
  347. body += getSpan('singlestat-panel-value', panel.valueFontSize, panel.colorValue, data.valueFormatted);
  348. if (panel.postfix) {
  349. body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.colorPostfix, panel.postfix);
  350. }
  351. body += '</div>';
  352. return body;
  353. }
  354. function getValueText() {
  355. let result = panel.prefix ? templateSrv.replace(panel.prefix, data.scopedVars) : '';
  356. result += data.valueFormatted;
  357. result += panel.postfix ? templateSrv.replace(panel.postfix, data.scopedVars) : '';
  358. return result;
  359. }
  360. function addGauge() {
  361. const width = elem.width();
  362. const height = elem.height();
  363. // Allow to use a bit more space for wide gauges
  364. const dimension = Math.min(width, height * 1.3);
  365. ctrl.invalidGaugeRange = false;
  366. if (panel.gauge.minValue > panel.gauge.maxValue) {
  367. ctrl.invalidGaugeRange = true;
  368. return;
  369. }
  370. const plotCanvas = $('<div></div>');
  371. const plotCss = {
  372. top: '5px',
  373. margin: 'auto',
  374. position: 'relative',
  375. height: height * 0.9 + 'px',
  376. width: dimension + 'px',
  377. };
  378. plotCanvas.css(plotCss);
  379. const thresholds = [];
  380. for (let 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. const bgColor = config.bootData.user.lightTheme ? 'rgb(230,230,230)' : 'rgb(38,38,38)';
  391. const fontScale = parseInt(panel.valueFontSize, 10) / 100;
  392. const fontSize = Math.min(dimension / 5, 100) * fontScale;
  393. // Reduce gauge width if threshold labels enabled
  394. const gaugeWidthReduceRatio = panel.gauge.thresholdLabels ? 1.5 : 1;
  395. const gaugeWidth = Math.min(dimension / 6, 60) / gaugeWidthReduceRatio;
  396. const thresholdMarkersWidth = gaugeWidth / 5;
  397. const thresholdLabelFontSize = fontSize / 2.5;
  398. const options = {
  399. series: {
  400. gauges: {
  401. gauge: {
  402. min: panel.gauge.minValue,
  403. max: panel.gauge.maxValue,
  404. background: { color: bgColor },
  405. border: { color: null },
  406. shadow: { show: false },
  407. width: gaugeWidth,
  408. },
  409. frame: { show: false },
  410. label: { show: false },
  411. layout: { margin: 0, thresholdWidth: 0 },
  412. cell: { border: { width: 0 } },
  413. threshold: {
  414. values: thresholds,
  415. label: {
  416. show: panel.gauge.thresholdLabels,
  417. margin: thresholdMarkersWidth + 1,
  418. font: { size: thresholdLabelFontSize },
  419. },
  420. show: panel.gauge.thresholdMarkers,
  421. width: thresholdMarkersWidth,
  422. },
  423. value: {
  424. color: panel.colorValue ? getColorForValue(data, data.valueRounded) : null,
  425. formatter: () => {
  426. return getValueText();
  427. },
  428. font: {
  429. size: fontSize,
  430. family: config.theme.typography.fontFamily.sansSerif,
  431. },
  432. },
  433. show: true,
  434. },
  435. },
  436. };
  437. elem.append(plotCanvas);
  438. const plotSeries = {
  439. data: [[0, data.value]],
  440. };
  441. $.plot(plotCanvas, [plotSeries], options);
  442. }
  443. function addSparkline() {
  444. const width = elem.width();
  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. const height = ctrl.height;
  452. const plotCanvas = $('<div></div>');
  453. const plotCss: any = {};
  454. plotCss.position = 'absolute';
  455. plotCss.bottom = '0px';
  456. if (panel.sparkline.full) {
  457. plotCss.left = '0px';
  458. plotCss.width = width + 'px';
  459. const dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5;
  460. plotCss.height = height - dynamicHeightMargin + 'px';
  461. } else {
  462. plotCss.left = '0px';
  463. plotCss.width = width + 'px';
  464. plotCss.height = Math.floor(height * 0.25) + 'px';
  465. }
  466. plotCanvas.css(plotCss);
  467. const options = {
  468. legend: { show: false },
  469. series: {
  470. lines: {
  471. show: true,
  472. fill: 1,
  473. lineWidth: 1,
  474. fillColor: getColorFromHexRgbOrName(panel.sparkline.fillColor, config.theme.type),
  475. },
  476. },
  477. yaxes: {
  478. show: false,
  479. min: panel.sparkline.ymin,
  480. max: panel.sparkline.ymax,
  481. },
  482. xaxis: {
  483. show: false,
  484. mode: 'time',
  485. min: ctrl.range.from.valueOf(),
  486. max: ctrl.range.to.valueOf(),
  487. },
  488. grid: { hoverable: false, show: false },
  489. };
  490. elem.append(plotCanvas);
  491. const plotSeries = {
  492. data: data.flotpairs,
  493. color: getColorFromHexRgbOrName(panel.sparkline.lineColor, config.theme.type),
  494. };
  495. $.plot(plotCanvas, [plotSeries], options);
  496. }
  497. function render() {
  498. if (!ctrl.data) {
  499. return;
  500. }
  501. data = ctrl.data;
  502. // get thresholds
  503. data.thresholds = panel.thresholds.split(',').map(strVale => {
  504. return Number(strVale.trim());
  505. });
  506. // Map panel colors to hex or rgb/a values
  507. data.colorMap = panel.colors.map(color =>
  508. getColorFromHexRgbOrName(
  509. color,
  510. config.bootData.user.lightTheme ? GrafanaThemeType.Light : GrafanaThemeType.Dark
  511. )
  512. );
  513. const body = panel.gauge.show ? '' : getBigValueHtml();
  514. if (panel.colorBackground) {
  515. const color = getColorForValue(data, data.value);
  516. console.log(color);
  517. if (color) {
  518. $panelContainer.css('background-color', color);
  519. if (scope.fullscreen) {
  520. elem.css('background-color', color);
  521. } else {
  522. elem.css('background-color', '');
  523. }
  524. }
  525. } else {
  526. $panelContainer.css('background-color', '');
  527. elem.css('background-color', '');
  528. }
  529. elem.html(body);
  530. if (panel.sparkline.show) {
  531. addSparkline();
  532. }
  533. if (panel.gauge.show) {
  534. addGauge();
  535. }
  536. elem.toggleClass('pointer', panel.links.length > 0);
  537. if (panel.links.length > 0) {
  538. linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], data.scopedVars);
  539. } else {
  540. linkInfo = null;
  541. }
  542. }
  543. function hookupDrilldownLinkTooltip() {
  544. // drilldown link tooltip
  545. const drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
  546. elem.mouseleave(() => {
  547. if (panel.links.length === 0) {
  548. return;
  549. }
  550. $timeout(() => {
  551. drilldownTooltip.detach();
  552. });
  553. });
  554. elem.click(evt => {
  555. if (!linkInfo) {
  556. return;
  557. }
  558. // ignore title clicks in title
  559. if ($(evt).parents('.panel-header').length > 0) {
  560. return;
  561. }
  562. if (linkInfo.target === '_blank') {
  563. window.open(linkInfo.href, '_blank');
  564. return;
  565. }
  566. if (linkInfo.href.indexOf('http') === 0) {
  567. window.location.href = linkInfo.href;
  568. } else {
  569. $timeout(() => {
  570. $location.url(linkInfo.href);
  571. });
  572. }
  573. drilldownTooltip.detach();
  574. });
  575. elem.mousemove(e => {
  576. if (!linkInfo) {
  577. return;
  578. }
  579. drilldownTooltip.text('click to go to: ' + linkInfo.title);
  580. drilldownTooltip.place_tt(e.pageX, e.pageY - 50);
  581. });
  582. }
  583. hookupDrilldownLinkTooltip();
  584. this.events.on('render', () => {
  585. render();
  586. ctrl.renderingCompleted();
  587. });
  588. }
  589. }
  590. function getColorForValue(data, value) {
  591. if (!_.isFinite(value)) {
  592. return null;
  593. }
  594. for (let i = data.thresholds.length; i > 0; i--) {
  595. if (value >= data.thresholds[i - 1]) {
  596. return data.colorMap[i];
  597. }
  598. }
  599. return _.first(data.colorMap);
  600. }
  601. export { SingleStatCtrl, SingleStatCtrl as PanelCtrl, getColorForValue };