datasource.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. import angular from 'angular';
  2. import {
  3. clone,
  4. compact,
  5. each,
  6. every,
  7. filter,
  8. findIndex,
  9. has,
  10. includes,
  11. isArray,
  12. isEmpty,
  13. map as _map,
  14. toPairs,
  15. } from 'lodash';
  16. import { lastValueFrom, Observable, of } from 'rxjs';
  17. import { catchError, map } from 'rxjs/operators';
  18. import {
  19. AnnotationEvent,
  20. DataQueryRequest,
  21. DataQueryResponse,
  22. DataSourceApi,
  23. dateMath,
  24. ScopedVars,
  25. } from '@grafana/data';
  26. import { FetchResponse, getBackendSrv } from '@grafana/runtime';
  27. import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';
  28. import { OpenTsdbOptions, OpenTsdbQuery } from './types';
  29. export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenTsdbOptions> {
  30. type: any;
  31. url: any;
  32. name: any;
  33. withCredentials: any;
  34. basicAuth: any;
  35. tsdbVersion: any;
  36. tsdbResolution: any;
  37. lookupLimit: any;
  38. tagKeys: any;
  39. aggregatorsPromise: any;
  40. filterTypesPromise: any;
  41. constructor(instanceSettings: any, private readonly templateSrv: TemplateSrv = getTemplateSrv()) {
  42. super(instanceSettings);
  43. this.type = 'opentsdb';
  44. this.url = instanceSettings.url;
  45. this.name = instanceSettings.name;
  46. this.withCredentials = instanceSettings.withCredentials;
  47. this.basicAuth = instanceSettings.basicAuth;
  48. instanceSettings.jsonData = instanceSettings.jsonData || {};
  49. this.tsdbVersion = instanceSettings.jsonData.tsdbVersion || 1;
  50. this.tsdbResolution = instanceSettings.jsonData.tsdbResolution || 1;
  51. this.lookupLimit = instanceSettings.jsonData.lookupLimit || 1000;
  52. this.tagKeys = {};
  53. this.aggregatorsPromise = null;
  54. this.filterTypesPromise = null;
  55. }
  56. // Called once per panel (graph)
  57. query(options: DataQueryRequest<OpenTsdbQuery>): Observable<DataQueryResponse> {
  58. const start = this.convertToTSDBTime(options.range.raw.from, false, options.timezone);
  59. const end = this.convertToTSDBTime(options.range.raw.to, true, options.timezone);
  60. const qs: any[] = [];
  61. each(options.targets, (target) => {
  62. if (!target.metric) {
  63. return;
  64. }
  65. qs.push(this.convertTargetToQuery(target, options, this.tsdbVersion));
  66. });
  67. const queries = compact(qs);
  68. // No valid targets, return the empty result to save a round trip.
  69. if (isEmpty(queries)) {
  70. return of({ data: [] });
  71. }
  72. const groupByTags: any = {};
  73. each(queries, (query) => {
  74. if (query.filters && query.filters.length > 0) {
  75. each(query.filters, (val) => {
  76. groupByTags[val.tagk] = true;
  77. });
  78. } else {
  79. each(query.tags, (val, key) => {
  80. groupByTags[key] = true;
  81. });
  82. }
  83. });
  84. options.targets = filter(options.targets, (query) => {
  85. return query.hide !== true;
  86. });
  87. return this.performTimeSeriesQuery(queries, start, end).pipe(
  88. catchError((err) => {
  89. // Throw the error message here instead of the whole object to workaround the error parsing error.
  90. throw err?.data?.error?.message || 'Error performing time series query.';
  91. }),
  92. map((response) => {
  93. const metricToTargetMapping = this.mapMetricsToTargets(response.data, options, this.tsdbVersion);
  94. const result = _map(response.data, (metricData: any, index: number) => {
  95. index = metricToTargetMapping[index];
  96. if (index === -1) {
  97. index = 0;
  98. }
  99. this._saveTagKeys(metricData);
  100. return this.transformMetricData(
  101. metricData,
  102. groupByTags,
  103. options.targets[index],
  104. options,
  105. this.tsdbResolution
  106. );
  107. });
  108. return { data: result };
  109. })
  110. );
  111. }
  112. annotationQuery(options: any): Promise<AnnotationEvent[]> {
  113. const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone);
  114. const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone);
  115. const qs = [];
  116. const eventList: any[] = [];
  117. qs.push({ aggregator: 'sum', metric: options.annotation.target });
  118. const queries = compact(qs);
  119. return lastValueFrom(
  120. this.performTimeSeriesQuery(queries, start, end).pipe(
  121. map((results) => {
  122. if (results.data[0]) {
  123. let annotationObject = results.data[0].annotations;
  124. if (options.annotation.isGlobal) {
  125. annotationObject = results.data[0].globalAnnotations;
  126. }
  127. if (annotationObject) {
  128. each(annotationObject, (annotation) => {
  129. const event = {
  130. text: annotation.description,
  131. time: Math.floor(annotation.startTime) * 1000,
  132. annotation: options.annotation,
  133. };
  134. eventList.push(event);
  135. });
  136. }
  137. }
  138. return eventList;
  139. })
  140. )
  141. );
  142. }
  143. targetContainsTemplate(target: any) {
  144. if (target.filters && target.filters.length > 0) {
  145. for (let i = 0; i < target.filters.length; i++) {
  146. if (this.templateSrv.containsTemplate(target.filters[i].filter)) {
  147. return true;
  148. }
  149. }
  150. }
  151. if (target.tags && Object.keys(target.tags).length > 0) {
  152. for (const tagKey in target.tags) {
  153. if (this.templateSrv.containsTemplate(target.tags[tagKey])) {
  154. return true;
  155. }
  156. }
  157. }
  158. return false;
  159. }
  160. performTimeSeriesQuery(queries: any[], start: any, end: any): Observable<FetchResponse> {
  161. let msResolution = false;
  162. if (this.tsdbResolution === 2) {
  163. msResolution = true;
  164. }
  165. const reqBody: any = {
  166. start: start,
  167. queries: queries,
  168. msResolution: msResolution,
  169. globalAnnotations: true,
  170. };
  171. if (this.tsdbVersion === 3) {
  172. reqBody.showQuery = true;
  173. }
  174. // Relative queries (e.g. last hour) don't include an end time
  175. if (end) {
  176. reqBody.end = end;
  177. }
  178. const options = {
  179. method: 'POST',
  180. url: this.url + '/api/query',
  181. data: reqBody,
  182. };
  183. this._addCredentialOptions(options);
  184. return getBackendSrv().fetch(options);
  185. }
  186. suggestTagKeys(metric: string | number) {
  187. return Promise.resolve(this.tagKeys[metric] || []);
  188. }
  189. _saveTagKeys(metricData: { tags: {}; aggregateTags: any; metric: string | number }) {
  190. const tagKeys = Object.keys(metricData.tags);
  191. each(metricData.aggregateTags, (tag) => {
  192. tagKeys.push(tag);
  193. });
  194. this.tagKeys[metricData.metric] = tagKeys;
  195. }
  196. _performSuggestQuery(query: string, type: string): Observable<any> {
  197. return this._get('/api/suggest', { type, q: query, max: this.lookupLimit }).pipe(
  198. map((result: any) => {
  199. return result.data;
  200. })
  201. );
  202. }
  203. _performMetricKeyValueLookup(metric: string, keys: any): Observable<any[]> {
  204. if (!metric || !keys) {
  205. return of([]);
  206. }
  207. const keysArray = keys.split(',').map((key: any) => {
  208. return key.trim();
  209. });
  210. const key = keysArray[0];
  211. let keysQuery = key + '=*';
  212. if (keysArray.length > 1) {
  213. keysQuery += ',' + keysArray.splice(1).join(',');
  214. }
  215. const m = metric + '{' + keysQuery + '}';
  216. return this._get('/api/search/lookup', { m: m, limit: this.lookupLimit }).pipe(
  217. map((result: any) => {
  218. result = result.data.results;
  219. const tagvs: any[] = [];
  220. each(result, (r) => {
  221. if (tagvs.indexOf(r.tags[key]) === -1) {
  222. tagvs.push(r.tags[key]);
  223. }
  224. });
  225. return tagvs;
  226. })
  227. );
  228. }
  229. _performMetricKeyLookup(metric: any): Observable<any[]> {
  230. if (!metric) {
  231. return of([]);
  232. }
  233. return this._get('/api/search/lookup', { m: metric, limit: 1000 }).pipe(
  234. map((result: any) => {
  235. result = result.data.results;
  236. const tagks: any[] = [];
  237. each(result, (r) => {
  238. each(r.tags, (tagv, tagk) => {
  239. if (tagks.indexOf(tagk) === -1) {
  240. tagks.push(tagk);
  241. }
  242. });
  243. });
  244. return tagks;
  245. })
  246. );
  247. }
  248. _get(
  249. relativeUrl: string,
  250. params?: { type?: string; q?: string; max?: number; m?: any; limit?: number }
  251. ): Observable<FetchResponse> {
  252. const options = {
  253. method: 'GET',
  254. url: this.url + relativeUrl,
  255. params: params,
  256. };
  257. this._addCredentialOptions(options);
  258. return getBackendSrv().fetch(options);
  259. }
  260. _addCredentialOptions(options: any) {
  261. if (this.basicAuth || this.withCredentials) {
  262. options.withCredentials = true;
  263. }
  264. if (this.basicAuth) {
  265. options.headers = { Authorization: this.basicAuth };
  266. }
  267. }
  268. metricFindQuery(query: string) {
  269. if (!query) {
  270. return Promise.resolve([]);
  271. }
  272. let interpolated;
  273. try {
  274. interpolated = this.templateSrv.replace(query, {}, 'distributed');
  275. } catch (err) {
  276. return Promise.reject(err);
  277. }
  278. const responseTransform = (result: any) => {
  279. return _map(result, (value) => {
  280. return { text: value };
  281. });
  282. };
  283. const metricsRegex = /metrics\((.*)\)/;
  284. const tagNamesRegex = /tag_names\((.*)\)/;
  285. const tagValuesRegex = /tag_values\((.*?),\s?(.*)\)/;
  286. const tagNamesSuggestRegex = /suggest_tagk\((.*)\)/;
  287. const tagValuesSuggestRegex = /suggest_tagv\((.*)\)/;
  288. const metricsQuery = interpolated.match(metricsRegex);
  289. if (metricsQuery) {
  290. return lastValueFrom(this._performSuggestQuery(metricsQuery[1], 'metrics').pipe(map(responseTransform)));
  291. }
  292. const tagNamesQuery = interpolated.match(tagNamesRegex);
  293. if (tagNamesQuery) {
  294. return lastValueFrom(this._performMetricKeyLookup(tagNamesQuery[1]).pipe(map(responseTransform)));
  295. }
  296. const tagValuesQuery = interpolated.match(tagValuesRegex);
  297. if (tagValuesQuery) {
  298. return lastValueFrom(
  299. this._performMetricKeyValueLookup(tagValuesQuery[1], tagValuesQuery[2]).pipe(map(responseTransform))
  300. );
  301. }
  302. const tagNamesSuggestQuery = interpolated.match(tagNamesSuggestRegex);
  303. if (tagNamesSuggestQuery) {
  304. return lastValueFrom(this._performSuggestQuery(tagNamesSuggestQuery[1], 'tagk').pipe(map(responseTransform)));
  305. }
  306. const tagValuesSuggestQuery = interpolated.match(tagValuesSuggestRegex);
  307. if (tagValuesSuggestQuery) {
  308. return lastValueFrom(this._performSuggestQuery(tagValuesSuggestQuery[1], 'tagv').pipe(map(responseTransform)));
  309. }
  310. return Promise.resolve([]);
  311. }
  312. testDatasource() {
  313. return lastValueFrom(
  314. this._performSuggestQuery('cpu', 'metrics').pipe(
  315. map(() => {
  316. return { status: 'success', message: 'Data source is working' };
  317. })
  318. )
  319. );
  320. }
  321. getAggregators() {
  322. if (this.aggregatorsPromise) {
  323. return this.aggregatorsPromise;
  324. }
  325. this.aggregatorsPromise = lastValueFrom(
  326. this._get('/api/aggregators').pipe(
  327. map((result: any) => {
  328. if (result.data && isArray(result.data)) {
  329. return result.data.sort();
  330. }
  331. return [];
  332. })
  333. )
  334. );
  335. return this.aggregatorsPromise;
  336. }
  337. getFilterTypes() {
  338. if (this.filterTypesPromise) {
  339. return this.filterTypesPromise;
  340. }
  341. this.filterTypesPromise = lastValueFrom(
  342. this._get('/api/config/filters').pipe(
  343. map((result: any) => {
  344. if (result.data) {
  345. return Object.keys(result.data).sort();
  346. }
  347. return [];
  348. })
  349. )
  350. );
  351. return this.filterTypesPromise;
  352. }
  353. transformMetricData(md: { dps: any }, groupByTags: any, target: any, options: any, tsdbResolution: number) {
  354. const metricLabel = this.createMetricLabel(md, target, groupByTags, options);
  355. const dps: any[] = [];
  356. // TSDB returns datapoints has a hash of ts => value.
  357. // Can't use pairs(invert()) because it stringifies keys/values
  358. each(md.dps, (v: any, k: number) => {
  359. if (tsdbResolution === 2) {
  360. dps.push([v, k * 1]);
  361. } else {
  362. dps.push([v, k * 1000]);
  363. }
  364. });
  365. return { target: metricLabel, datapoints: dps };
  366. }
  367. createMetricLabel(
  368. md: { dps?: any; tags?: any; metric?: any },
  369. target: { alias: string },
  370. groupByTags: any,
  371. options: { scopedVars: any }
  372. ) {
  373. if (target.alias) {
  374. const scopedVars = clone(options.scopedVars || {});
  375. each(md.tags, (value, key) => {
  376. scopedVars['tag_' + key] = { value: value };
  377. });
  378. return this.templateSrv.replace(target.alias, scopedVars);
  379. }
  380. let label = md.metric;
  381. const tagData: any[] = [];
  382. if (!isEmpty(md.tags)) {
  383. each(toPairs(md.tags), (tag) => {
  384. if (has(groupByTags, tag[0])) {
  385. tagData.push(tag[0] + '=' + tag[1]);
  386. }
  387. });
  388. }
  389. if (!isEmpty(tagData)) {
  390. label += '{' + tagData.join(', ') + '}';
  391. }
  392. return label;
  393. }
  394. convertTargetToQuery(target: any, options: any, tsdbVersion: number) {
  395. if (!target.metric || target.hide) {
  396. return null;
  397. }
  398. const query: any = {
  399. metric: this.templateSrv.replace(target.metric, options.scopedVars, 'pipe'),
  400. aggregator: 'avg',
  401. };
  402. if (target.aggregator) {
  403. query.aggregator = this.templateSrv.replace(target.aggregator);
  404. }
  405. if (target.shouldComputeRate) {
  406. query.rate = true;
  407. query.rateOptions = {
  408. counter: !!target.isCounter,
  409. };
  410. if (target.counterMax && target.counterMax.length) {
  411. query.rateOptions.counterMax = parseInt(target.counterMax, 10);
  412. }
  413. if (target.counterResetValue && target.counterResetValue.length) {
  414. query.rateOptions.resetValue = parseInt(target.counterResetValue, 10);
  415. }
  416. if (tsdbVersion >= 2) {
  417. query.rateOptions.dropResets =
  418. !query.rateOptions.counterMax && (!query.rateOptions.ResetValue || query.rateOptions.ResetValue === 0);
  419. }
  420. }
  421. if (!target.disableDownsampling) {
  422. let interval = this.templateSrv.replace(target.downsampleInterval || options.interval);
  423. if (interval.match(/\.[0-9]+s/)) {
  424. interval = parseFloat(interval) * 1000 + 'ms';
  425. }
  426. query.downsample = interval + '-' + target.downsampleAggregator;
  427. if (target.downsampleFillPolicy && target.downsampleFillPolicy !== 'none') {
  428. query.downsample += '-' + target.downsampleFillPolicy;
  429. }
  430. }
  431. if (target.filters && target.filters.length > 0) {
  432. query.filters = angular.copy(target.filters);
  433. if (query.filters) {
  434. for (const filterKey in query.filters) {
  435. query.filters[filterKey].filter = this.templateSrv.replace(
  436. query.filters[filterKey].filter,
  437. options.scopedVars,
  438. 'pipe'
  439. );
  440. }
  441. }
  442. } else {
  443. query.tags = angular.copy(target.tags);
  444. if (query.tags) {
  445. for (const tagKey in query.tags) {
  446. query.tags[tagKey] = this.templateSrv.replace(query.tags[tagKey], options.scopedVars, 'pipe');
  447. }
  448. }
  449. }
  450. if (target.explicitTags) {
  451. query.explicitTags = true;
  452. }
  453. return query;
  454. }
  455. mapMetricsToTargets(metrics: any, options: any, tsdbVersion: number) {
  456. let interpolatedTagValue, arrTagV;
  457. return _map(metrics, (metricData) => {
  458. if (tsdbVersion === 3) {
  459. return metricData.query.index;
  460. } else {
  461. return findIndex(options.targets as any[], (target) => {
  462. if (target.filters && target.filters.length > 0) {
  463. return target.metric === metricData.metric;
  464. } else {
  465. return (
  466. target.metric === metricData.metric &&
  467. every(target.tags, (tagV, tagK) => {
  468. interpolatedTagValue = this.templateSrv.replace(tagV, options.scopedVars, 'pipe');
  469. arrTagV = interpolatedTagValue.split('|');
  470. return includes(arrTagV, metricData.tags[tagK]) || interpolatedTagValue === '*';
  471. })
  472. );
  473. }
  474. });
  475. }
  476. });
  477. }
  478. interpolateVariablesInQueries(queries: OpenTsdbQuery[], scopedVars: ScopedVars): OpenTsdbQuery[] {
  479. if (!queries.length) {
  480. return queries;
  481. }
  482. return queries.map((query) => ({
  483. ...query,
  484. metric: this.templateSrv.replace(query.metric, scopedVars),
  485. }));
  486. }
  487. convertToTSDBTime(date: any, roundUp: any, timezone: any) {
  488. if (date === 'now') {
  489. return null;
  490. }
  491. date = dateMath.parse(date, roundUp, timezone);
  492. return date.valueOf();
  493. }
  494. }