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. class SingleStatCtrl extends MetricsPanelCtrl {
  13. static templateUrl = 'module.html';
  14. dataType = 'timeseries';
  15. series: any[];
  16. data: any;
  17. fontSizes: any[];
  18. unitFormats: any[];
  19. invalidGaugeRange: boolean;
  20. panel: any;
  21. events: any;
  22. valueNameOptions: any[] = [
  23. { value: 'min', text: 'Min' },
  24. { value: 'max', text: 'Max' },
  25. { value: 'avg', text: 'Average' },
  26. { value: 'current', text: 'Current' },
  27. { value: 'total', text: 'Total' },
  28. { value: 'name', text: 'Name' },
  29. { value: 'first', text: 'First' },
  30. { value: 'delta', text: 'Delta' },
  31. { value: 'diff', text: 'Difference' },
  32. { value: 'range', text: 'Range' },
  33. { value: 'last_time', text: 'Time of last point' },
  34. ];
  35. tableColumnOptions: any;
  36. // Set and populate defaults
  37. panelDefaults = {
  38. links: [],
  39. datasource: null,
  40. maxDataPoints: 100,
  41. interval: null,
  42. targets: [{}],
  43. cacheTimeout: null,
  44. format: 'none',
  45. prefix: '',
  46. postfix: '',
  47. nullText: null,
  48. valueMaps: [{ value: 'null', op: '=', text: 'N/A' }],
  49. mappingTypes: [{ name: 'value to text', value: 1 }, { name: 'range to text', value: 2 }],
  50. rangeMaps: [{ from: 'null', to: 'null', text: 'N/A' }],
  51. mappingType: 1,
  52. nullPointMode: 'connected',
  53. valueName: 'avg',
  54. prefixFontSize: '50%',
  55. valueFontSize: '80%',
  56. postfixFontSize: '50%',
  57. thresholds: '',
  58. colorBackground: false,
  59. colorValue: false,
  60. colors: ['#299c46', 'rgba(237, 129, 40, 0.89)', '#d44a3a'],
  61. sparkline: {
  62. show: false,
  63. full: false,
  64. lineColor: 'rgb(31, 120, 193)',
  65. fillColor: 'rgba(31, 118, 189, 0.18)',
  66. },
  67. gauge: {
  68. show: false,
  69. minValue: 0,
  70. maxValue: 100,
  71. thresholdMarkers: true,
  72. thresholdLabels: false,
  73. },
  74. tableColumn: '',
  75. };
  76. /** @ngInject */
  77. constructor($scope, $injector, private linkSrv, private $sanitize) {
  78. super($scope, $injector);
  79. _.defaults(this.panel, this.panelDefaults);
  80. this.events.on('data-received', this.onDataReceived.bind(this));
  81. this.events.on('data-error', this.onDataError.bind(this));
  82. this.events.on('data-snapshot-load', this.onDataReceived.bind(this));
  83. this.events.on('init-edit-mode', this.onInitEditMode.bind(this));
  84. this.onSparklineColorChange = this.onSparklineColorChange.bind(this);
  85. this.onSparklineFillChange = this.onSparklineFillChange.bind(this);
  86. }
  87. onInitEditMode() {
  88. this.fontSizes = ['20%', '30%', '50%', '70%', '80%', '100%', '110%', '120%', '150%', '170%', '200%'];
  89. this.addEditorTab('Options', 'public/app/plugins/panel/singlestat/editor.html', 2);
  90. this.addEditorTab('Value Mappings', 'public/app/plugins/panel/singlestat/mappings.html', 3);
  91. this.unitFormats = kbn.getUnitFormats();
  92. }
  93. setUnitFormat(subItem) {
  94. this.panel.format = subItem.value;
  95. this.refresh();
  96. }
  97. onDataError(err) {
  98. this.onDataReceived([]);
  99. }
  100. onDataReceived(dataList) {
  101. const data: any = {
  102. scopedVars: _.extend({}, this.panel.scopedVars),
  103. };
  104. if (dataList.length > 0 && isTableData(dataList[0])) {
  105. this.dataType = 'table';
  106. const tableData = dataList.map(this.tableHandler.bind(this));
  107. this.setTableValues(tableData, data);
  108. } else {
  109. this.dataType = 'timeseries';
  110. this.series = dataList.map(this.seriesHandler.bind(this));
  111. this.setValues(data);
  112. }
  113. this.data = data;
  114. this.render();
  115. }
  116. seriesHandler(seriesData) {
  117. const series = new TimeSeries({
  118. datapoints: seriesData.datapoints || [],
  119. alias: seriesData.target,
  120. });
  121. series.flotpairs = series.getFlotPairs(this.panel.nullPointMode);
  122. return series;
  123. }
  124. tableHandler(tableData) {
  125. const datapoints = [];
  126. const columnNames = {};
  127. tableData.columns.forEach((column, columnIndex) => {
  128. columnNames[columnIndex] = column.text;
  129. });
  130. this.tableColumnOptions = columnNames;
  131. if (!_.find(tableData.columns, ['text', this.panel.tableColumn])) {
  132. this.setTableColumnToSensibleDefault(tableData);
  133. }
  134. tableData.rows.forEach(row => {
  135. const datapoint = {};
  136. row.forEach((value, columnIndex) => {
  137. const key = columnNames[columnIndex];
  138. datapoint[key] = value;
  139. });
  140. datapoints.push(datapoint);
  141. });
  142. return datapoints;
  143. }
  144. setTableColumnToSensibleDefault(tableData) {
  145. if (tableData.columns.length === 1) {
  146. this.panel.tableColumn = tableData.columns[0].text;
  147. } else {
  148. this.panel.tableColumn = _.find(tableData.columns, col => {
  149. return col.type !== 'time';
  150. }).text;
  151. }
  152. }
  153. setTableValues(tableData, data) {
  154. if (!tableData || tableData.length === 0) {
  155. return;
  156. }
  157. if (tableData[0].length === 0 || tableData[0][0][this.panel.tableColumn] === undefined) {
  158. return;
  159. }
  160. const datapoint = tableData[0][0];
  161. data.value = datapoint[this.panel.tableColumn];
  162. if (_.isString(data.value)) {
  163. data.valueFormatted = _.escape(data.value);
  164. data.value = 0;
  165. data.valueRounded = 0;
  166. } else {
  167. const decimalInfo = getDecimalsForValue(data.value);
  168. const formatFunc = getValueFormat(this.panel.format);
  169. data.valueFormatted = formatFunc(
  170. datapoint[this.panel.tableColumn],
  171. decimalInfo.decimals,
  172. decimalInfo.scaledDecimals
  173. );
  174. data.valueRounded = kbn.roundValue(data.value, this.panel.decimals || 0);
  175. }
  176. this.setValueMapping(data);
  177. }
  178. canModifyText() {
  179. return !this.panel.gauge.show;
  180. }
  181. setColoring(options) {
  182. if (options.background) {
  183. this.panel.colorValue = false;
  184. this.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
  185. } else {
  186. this.panel.colorBackground = false;
  187. this.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
  188. }
  189. this.render();
  190. }
  191. invertColorOrder() {
  192. const tmp = this.panel.colors[0];
  193. this.panel.colors[0] = this.panel.colors[2];
  194. this.panel.colors[2] = tmp;
  195. this.render();
  196. }
  197. onColorChange(panelColorIndex) {
  198. return color => {
  199. this.panel.colors[panelColorIndex] = color;
  200. this.render();
  201. };
  202. }
  203. onSparklineColorChange(newColor) {
  204. this.panel.sparkline.lineColor = newColor;
  205. this.render();
  206. }
  207. onSparklineFillChange(newColor) {
  208. this.panel.sparkline.fillColor = newColor;
  209. this.render();
  210. }
  211. setValues(data) {
  212. data.flotpairs = [];
  213. if (this.series.length > 1) {
  214. const error: any = new Error();
  215. error.message = 'Multiple Series Error';
  216. error.data =
  217. 'Metric query returns ' +
  218. this.series.length +
  219. ' series. Single Stat Panel expects a single series.\n\nResponse:\n' +
  220. JSON.stringify(this.series);
  221. throw error;
  222. }
  223. if (this.series && this.series.length > 0) {
  224. const lastPoint = _.last(this.series[0].datapoints);
  225. const lastValue = _.isArray(lastPoint) ? lastPoint[0] : null;
  226. const formatFunc = getValueFormat(this.panel.format);
  227. if (this.panel.valueName === 'name') {
  228. data.value = 0;
  229. data.valueRounded = 0;
  230. data.valueFormatted = this.series[0].alias;
  231. } else if (_.isString(lastValue)) {
  232. data.value = 0;
  233. data.valueFormatted = _.escape(lastValue);
  234. data.valueRounded = 0;
  235. } else if (this.panel.valueName === 'last_time') {
  236. data.value = lastPoint[1];
  237. data.valueRounded = data.value;
  238. data.valueFormatted = formatFunc(data.value, 0, 0, this.dashboard.isTimezoneUtc());
  239. } else {
  240. data.value = this.series[0].stats[this.panel.valueName];
  241. data.flotpairs = this.series[0].flotpairs;
  242. let decimals = this.panel.decimals;
  243. let scaledDecimals = 0;
  244. if (!this.panel.decimals) {
  245. const decimalInfo = getDecimalsForValue(data.value);
  246. decimals = decimalInfo.decimals;
  247. scaledDecimals = decimalInfo.scaledDecimals;
  248. }
  249. data.valueFormatted = formatFunc(data.value, decimals, scaledDecimals, this.dashboard.isTimezoneUtc());
  250. data.valueRounded = kbn.roundValue(data.value, 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, fontSize, applyColoring, value) {
  335. value = $sanitize(templateSrv.replace(value, data.scopedVars));
  336. value = applyColoring ? applyColoringThresholds(value) : value;
  337. return '<span class="' + className + '" style="font-size:' + fontSize + '">' + value + '</span>';
  338. }
  339. function getBigValueHtml() {
  340. let body = '<div class="singlestat-panel-value-container">';
  341. if (panel.prefix) {
  342. body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.colorPrefix, panel.prefix);
  343. }
  344. body += getSpan('singlestat-panel-value', panel.valueFontSize, panel.colorValue, data.valueFormatted);
  345. if (panel.postfix) {
  346. body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.colorPostfix, panel.postfix);
  347. }
  348. body += '</div>';
  349. return body;
  350. }
  351. function getValueText() {
  352. let result = panel.prefix ? templateSrv.replace(panel.prefix, data.scopedVars) : '';
  353. result += data.valueFormatted;
  354. result += panel.postfix ? templateSrv.replace(panel.postfix, data.scopedVars) : '';
  355. return result;
  356. }
  357. function addGauge() {
  358. const width = elem.width();
  359. const height = elem.height();
  360. // Allow to use a bit more space for wide gauges
  361. const dimension = Math.min(width, height * 1.3);
  362. ctrl.invalidGaugeRange = false;
  363. if (panel.gauge.minValue > panel.gauge.maxValue) {
  364. ctrl.invalidGaugeRange = true;
  365. return;
  366. }
  367. const plotCanvas = $('<div></div>');
  368. const plotCss = {
  369. top: '10px',
  370. margin: 'auto',
  371. position: 'relative',
  372. height: height * 0.9 + 'px',
  373. width: dimension + 'px',
  374. };
  375. plotCanvas.css(plotCss);
  376. const thresholds = [];
  377. for (let i = 0; i < data.thresholds.length; i++) {
  378. thresholds.push({
  379. value: data.thresholds[i],
  380. color: data.colorMap[i],
  381. });
  382. }
  383. thresholds.push({
  384. value: panel.gauge.maxValue,
  385. color: data.colorMap[data.colorMap.length - 1],
  386. });
  387. const bgColor = config.bootData.user.lightTheme ? 'rgb(230,230,230)' : 'rgb(38,38,38)';
  388. const fontScale = parseInt(panel.valueFontSize, 10) / 100;
  389. const fontSize = Math.min(dimension / 5, 100) * fontScale;
  390. // Reduce gauge width if threshold labels enabled
  391. const gaugeWidthReduceRatio = panel.gauge.thresholdLabels ? 1.5 : 1;
  392. const gaugeWidth = Math.min(dimension / 6, 60) / gaugeWidthReduceRatio;
  393. const thresholdMarkersWidth = gaugeWidth / 5;
  394. const thresholdLabelFontSize = fontSize / 2.5;
  395. const options = {
  396. series: {
  397. gauges: {
  398. gauge: {
  399. min: panel.gauge.minValue,
  400. max: panel.gauge.maxValue,
  401. background: { color: bgColor },
  402. border: { color: null },
  403. shadow: { show: false },
  404. width: gaugeWidth,
  405. },
  406. frame: { show: false },
  407. label: { show: false },
  408. layout: { margin: 0, thresholdWidth: 0 },
  409. cell: { border: { width: 0 } },
  410. threshold: {
  411. values: thresholds,
  412. label: {
  413. show: panel.gauge.thresholdLabels,
  414. margin: thresholdMarkersWidth + 1,
  415. font: { size: thresholdLabelFontSize },
  416. },
  417. show: panel.gauge.thresholdMarkers,
  418. width: thresholdMarkersWidth,
  419. },
  420. value: {
  421. color: panel.colorValue ? getColorForValue(data, data.valueRounded) : null,
  422. formatter: () => {
  423. return getValueText();
  424. },
  425. font: {
  426. size: fontSize,
  427. family: '"Helvetica Neue", Helvetica, Arial, sans-serif',
  428. },
  429. },
  430. show: true,
  431. },
  432. },
  433. };
  434. elem.append(plotCanvas);
  435. const plotSeries = {
  436. data: [[0, data.value]],
  437. };
  438. $.plot(plotCanvas, [plotSeries], options);
  439. }
  440. function addSparkline() {
  441. const width = elem.width() + 20;
  442. if (width < 30) {
  443. // element has not gotten it's width yet
  444. // delay sparkline render
  445. setTimeout(addSparkline, 30);
  446. return;
  447. }
  448. const height = ctrl.height;
  449. const plotCanvas = $('<div></div>');
  450. const plotCss: any = {};
  451. plotCss.position = 'absolute';
  452. if (panel.sparkline.full) {
  453. plotCss.bottom = '5px';
  454. plotCss.left = '-5px';
  455. plotCss.width = width - 10 + 'px';
  456. const dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5;
  457. plotCss.height = height - dynamicHeightMargin + 'px';
  458. } else {
  459. plotCss.bottom = '0px';
  460. plotCss.left = '-5px';
  461. plotCss.width = width - 10 + '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 };