module.ts 20 KB

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