module.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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, this.panel.decimals);
  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, decimalInfo.decimals);
  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. const decimalInfo = getDecimalsForValue(data.value, this.panel.decimals);
  243. data.valueFormatted = formatFunc(
  244. data.value,
  245. decimalInfo.decimals,
  246. decimalInfo.scaledDecimals,
  247. this.dashboard.isTimezoneUtc()
  248. );
  249. data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals);
  250. }
  251. // Add $__name variable for using in prefix or postfix
  252. data.scopedVars['__name'] = { value: this.series[0].label };
  253. }
  254. this.setValueMapping(data);
  255. }
  256. setValueMapping(data) {
  257. // check value to text mappings if its enabled
  258. if (this.panel.mappingType === 1) {
  259. for (let i = 0; i < this.panel.valueMaps.length; i++) {
  260. const map = this.panel.valueMaps[i];
  261. // special null case
  262. if (map.value === 'null') {
  263. if (data.value === null || data.value === void 0) {
  264. data.valueFormatted = map.text;
  265. return;
  266. }
  267. continue;
  268. }
  269. // value/number to text mapping
  270. const value = parseFloat(map.value);
  271. if (value === data.valueRounded) {
  272. data.valueFormatted = map.text;
  273. return;
  274. }
  275. }
  276. } else if (this.panel.mappingType === 2) {
  277. for (let i = 0; i < this.panel.rangeMaps.length; i++) {
  278. const map = this.panel.rangeMaps[i];
  279. // special null case
  280. if (map.from === 'null' && map.to === 'null') {
  281. if (data.value === null || data.value === void 0) {
  282. data.valueFormatted = map.text;
  283. return;
  284. }
  285. continue;
  286. }
  287. // value/number to range mapping
  288. const from = parseFloat(map.from);
  289. const to = parseFloat(map.to);
  290. if (to >= data.valueRounded && from <= data.valueRounded) {
  291. data.valueFormatted = map.text;
  292. return;
  293. }
  294. }
  295. }
  296. if (data.value === null || data.value === void 0) {
  297. data.valueFormatted = 'no value';
  298. }
  299. }
  300. removeValueMap(map) {
  301. const index = _.indexOf(this.panel.valueMaps, map);
  302. this.panel.valueMaps.splice(index, 1);
  303. this.render();
  304. }
  305. addValueMap() {
  306. this.panel.valueMaps.push({ value: '', op: '=', text: '' });
  307. }
  308. removeRangeMap(rangeMap) {
  309. const index = _.indexOf(this.panel.rangeMaps, rangeMap);
  310. this.panel.rangeMaps.splice(index, 1);
  311. this.render();
  312. }
  313. addRangeMap() {
  314. this.panel.rangeMaps.push({ from: '', to: '', text: '' });
  315. }
  316. link(scope, elem, attrs, ctrl) {
  317. const $location = this.$location;
  318. const linkSrv = this.linkSrv;
  319. const $timeout = this.$timeout;
  320. const $sanitize = this.$sanitize;
  321. const panel = ctrl.panel;
  322. const templateSrv = this.templateSrv;
  323. let data, linkInfo;
  324. const $panelContainer = elem.find('.panel-container');
  325. elem = elem.find('.singlestat-panel');
  326. function applyColoringThresholds(valueString) {
  327. const color = getColorForValue(data, data.value);
  328. if (color) {
  329. return '<span style="color:' + color + '">' + valueString + '</span>';
  330. }
  331. return valueString;
  332. }
  333. function getSpan(className, fontSize, applyColoring, value) {
  334. value = $sanitize(templateSrv.replace(value, data.scopedVars));
  335. value = applyColoring ? applyColoringThresholds(value) : value;
  336. return '<span class="' + className + '" style="font-size:' + fontSize + '">' + value + '</span>';
  337. }
  338. function getBigValueHtml() {
  339. let body = '<div class="singlestat-panel-value-container">';
  340. if (panel.prefix) {
  341. body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.colorPrefix, panel.prefix);
  342. }
  343. body += getSpan('singlestat-panel-value', panel.valueFontSize, panel.colorValue, data.valueFormatted);
  344. if (panel.postfix) {
  345. body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.colorPostfix, panel.postfix);
  346. }
  347. body += '</div>';
  348. return body;
  349. }
  350. function getValueText() {
  351. let result = panel.prefix ? templateSrv.replace(panel.prefix, data.scopedVars) : '';
  352. result += data.valueFormatted;
  353. result += panel.postfix ? templateSrv.replace(panel.postfix, data.scopedVars) : '';
  354. return result;
  355. }
  356. function addGauge() {
  357. const width = elem.width();
  358. const height = elem.height();
  359. // Allow to use a bit more space for wide gauges
  360. const dimension = Math.min(width, height * 1.3);
  361. ctrl.invalidGaugeRange = false;
  362. if (panel.gauge.minValue > panel.gauge.maxValue) {
  363. ctrl.invalidGaugeRange = true;
  364. return;
  365. }
  366. const plotCanvas = $('<div></div>');
  367. const plotCss = {
  368. top: '10px',
  369. margin: 'auto',
  370. position: 'relative',
  371. height: height * 0.9 + 'px',
  372. width: dimension + 'px',
  373. };
  374. plotCanvas.css(plotCss);
  375. const thresholds = [];
  376. for (let i = 0; i < data.thresholds.length; i++) {
  377. thresholds.push({
  378. value: data.thresholds[i],
  379. color: data.colorMap[i],
  380. });
  381. }
  382. thresholds.push({
  383. value: panel.gauge.maxValue,
  384. color: data.colorMap[data.colorMap.length - 1],
  385. });
  386. const bgColor = config.bootData.user.lightTheme ? 'rgb(230,230,230)' : 'rgb(38,38,38)';
  387. const fontScale = parseInt(panel.valueFontSize, 10) / 100;
  388. const fontSize = Math.min(dimension / 5, 100) * fontScale;
  389. // Reduce gauge width if threshold labels enabled
  390. const gaugeWidthReduceRatio = panel.gauge.thresholdLabels ? 1.5 : 1;
  391. const gaugeWidth = Math.min(dimension / 6, 60) / gaugeWidthReduceRatio;
  392. const thresholdMarkersWidth = gaugeWidth / 5;
  393. const thresholdLabelFontSize = fontSize / 2.5;
  394. const options = {
  395. series: {
  396. gauges: {
  397. gauge: {
  398. min: panel.gauge.minValue,
  399. max: panel.gauge.maxValue,
  400. background: { color: bgColor },
  401. border: { color: null },
  402. shadow: { show: false },
  403. width: gaugeWidth,
  404. },
  405. frame: { show: false },
  406. label: { show: false },
  407. layout: { margin: 0, thresholdWidth: 0 },
  408. cell: { border: { width: 0 } },
  409. threshold: {
  410. values: thresholds,
  411. label: {
  412. show: panel.gauge.thresholdLabels,
  413. margin: thresholdMarkersWidth + 1,
  414. font: { size: thresholdLabelFontSize },
  415. },
  416. show: panel.gauge.thresholdMarkers,
  417. width: thresholdMarkersWidth,
  418. },
  419. value: {
  420. color: panel.colorValue ? getColorForValue(data, data.valueRounded) : null,
  421. formatter: () => {
  422. return getValueText();
  423. },
  424. font: {
  425. size: fontSize,
  426. family: '"Helvetica Neue", Helvetica, Arial, sans-serif',
  427. },
  428. },
  429. show: true,
  430. },
  431. },
  432. };
  433. elem.append(plotCanvas);
  434. const plotSeries = {
  435. data: [[0, data.value]],
  436. };
  437. $.plot(plotCanvas, [plotSeries], options);
  438. }
  439. function addSparkline() {
  440. const width = elem.width() + 20;
  441. if (width < 30) {
  442. // element has not gotten it's width yet
  443. // delay sparkline render
  444. setTimeout(addSparkline, 30);
  445. return;
  446. }
  447. const height = ctrl.height;
  448. const plotCanvas = $('<div></div>');
  449. const plotCss: any = {};
  450. plotCss.position = 'absolute';
  451. if (panel.sparkline.full) {
  452. plotCss.bottom = '5px';
  453. plotCss.left = '-5px';
  454. plotCss.width = width - 10 + 'px';
  455. const dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5;
  456. plotCss.height = height - dynamicHeightMargin + 'px';
  457. } else {
  458. plotCss.bottom = '0px';
  459. plotCss.left = '-5px';
  460. plotCss.width = width - 10 + 'px';
  461. plotCss.height = Math.floor(height * 0.25) + 'px';
  462. }
  463. plotCanvas.css(plotCss);
  464. const options = {
  465. legend: { show: false },
  466. series: {
  467. lines: {
  468. show: true,
  469. fill: 1,
  470. zero: false,
  471. lineWidth: 1,
  472. fillColor: getColorFromHexRgbOrName(panel.sparkline.fillColor, config.theme.type),
  473. },
  474. },
  475. yaxes: { show: false },
  476. xaxis: {
  477. show: false,
  478. mode: 'time',
  479. min: ctrl.range.from.valueOf(),
  480. max: ctrl.range.to.valueOf(),
  481. },
  482. grid: { hoverable: false, show: false },
  483. };
  484. elem.append(plotCanvas);
  485. const plotSeries = {
  486. data: data.flotpairs,
  487. color: getColorFromHexRgbOrName(panel.sparkline.lineColor, config.theme.type),
  488. };
  489. $.plot(plotCanvas, [plotSeries], options);
  490. }
  491. function render() {
  492. if (!ctrl.data) {
  493. return;
  494. }
  495. data = ctrl.data;
  496. // get thresholds
  497. data.thresholds = panel.thresholds.split(',').map(strVale => {
  498. return Number(strVale.trim());
  499. });
  500. // Map panel colors to hex or rgb/a values
  501. data.colorMap = panel.colors.map(color =>
  502. getColorFromHexRgbOrName(
  503. color,
  504. config.bootData.user.lightTheme ? GrafanaThemeType.Light : GrafanaThemeType.Dark
  505. )
  506. );
  507. const body = panel.gauge.show ? '' : getBigValueHtml();
  508. if (panel.colorBackground) {
  509. const color = getColorForValue(data, data.value);
  510. console.log(color);
  511. if (color) {
  512. $panelContainer.css('background-color', color);
  513. if (scope.fullscreen) {
  514. elem.css('background-color', color);
  515. } else {
  516. elem.css('background-color', '');
  517. }
  518. }
  519. } else {
  520. $panelContainer.css('background-color', '');
  521. elem.css('background-color', '');
  522. }
  523. elem.html(body);
  524. if (panel.sparkline.show) {
  525. addSparkline();
  526. }
  527. if (panel.gauge.show) {
  528. addGauge();
  529. }
  530. elem.toggleClass('pointer', panel.links.length > 0);
  531. if (panel.links.length > 0) {
  532. linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], data.scopedVars);
  533. } else {
  534. linkInfo = null;
  535. }
  536. }
  537. function hookupDrilldownLinkTooltip() {
  538. // drilldown link tooltip
  539. const drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
  540. elem.mouseleave(() => {
  541. if (panel.links.length === 0) {
  542. return;
  543. }
  544. $timeout(() => {
  545. drilldownTooltip.detach();
  546. });
  547. });
  548. elem.click(evt => {
  549. if (!linkInfo) {
  550. return;
  551. }
  552. // ignore title clicks in title
  553. if ($(evt).parents('.panel-header').length > 0) {
  554. return;
  555. }
  556. if (linkInfo.target === '_blank') {
  557. window.open(linkInfo.href, '_blank');
  558. return;
  559. }
  560. if (linkInfo.href.indexOf('http') === 0) {
  561. window.location.href = linkInfo.href;
  562. } else {
  563. $timeout(() => {
  564. $location.url(linkInfo.href);
  565. });
  566. }
  567. drilldownTooltip.detach();
  568. });
  569. elem.mousemove(e => {
  570. if (!linkInfo) {
  571. return;
  572. }
  573. drilldownTooltip.text('click to go to: ' + linkInfo.title);
  574. drilldownTooltip.place_tt(e.pageX, e.pageY - 50);
  575. });
  576. }
  577. hookupDrilldownLinkTooltip();
  578. this.events.on('render', () => {
  579. render();
  580. ctrl.renderingCompleted();
  581. });
  582. }
  583. }
  584. function getColorForValue(data, value) {
  585. if (!_.isFinite(value)) {
  586. return null;
  587. }
  588. for (let i = data.thresholds.length; i > 0; i--) {
  589. if (value >= data.thresholds[i - 1]) {
  590. return data.colorMap[i];
  591. }
  592. }
  593. return _.first(data.colorMap);
  594. }
  595. export { SingleStatCtrl, SingleStatCtrl as PanelCtrl, getColorForValue };