datasource.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import angular from 'angular';
  2. import _ from 'lodash';
  3. import { ElasticResponse } from './elastic_response';
  4. import { IndexPattern } from './index_pattern';
  5. import { ElasticQueryBuilder } from './query_builder';
  6. import { toUtc } from '@grafana/ui/src/utils/moment_wrapper';
  7. export class ElasticDatasource {
  8. basicAuth: string;
  9. withCredentials: boolean;
  10. url: string;
  11. name: string;
  12. index: string;
  13. timeField: string;
  14. esVersion: number;
  15. interval: string;
  16. maxConcurrentShardRequests: number;
  17. queryBuilder: ElasticQueryBuilder;
  18. indexPattern: IndexPattern;
  19. /** @ngInject */
  20. constructor(instanceSettings, private $q, private backendSrv, private templateSrv, private timeSrv) {
  21. this.basicAuth = instanceSettings.basicAuth;
  22. this.withCredentials = instanceSettings.withCredentials;
  23. this.url = instanceSettings.url;
  24. this.name = instanceSettings.name;
  25. this.index = instanceSettings.index;
  26. this.timeField = instanceSettings.jsonData.timeField;
  27. this.esVersion = instanceSettings.jsonData.esVersion;
  28. this.indexPattern = new IndexPattern(instanceSettings.index, instanceSettings.jsonData.interval);
  29. this.interval = instanceSettings.jsonData.timeInterval;
  30. this.maxConcurrentShardRequests = instanceSettings.jsonData.maxConcurrentShardRequests;
  31. this.queryBuilder = new ElasticQueryBuilder({
  32. timeField: this.timeField,
  33. esVersion: this.esVersion,
  34. });
  35. }
  36. private request(method, url, data?) {
  37. const options: any = {
  38. url: this.url + '/' + url,
  39. method: method,
  40. data: data,
  41. };
  42. if (this.basicAuth || this.withCredentials) {
  43. options.withCredentials = true;
  44. }
  45. if (this.basicAuth) {
  46. options.headers = {
  47. Authorization: this.basicAuth,
  48. };
  49. }
  50. return this.backendSrv.datasourceRequest(options);
  51. }
  52. private get(url) {
  53. const range = this.timeSrv.timeRange();
  54. const indexList = this.indexPattern.getIndexList(range.from.valueOf(), range.to.valueOf());
  55. if (_.isArray(indexList) && indexList.length) {
  56. return this.request('GET', indexList[0] + url).then(results => {
  57. results.data.$$config = results.config;
  58. return results.data;
  59. });
  60. } else {
  61. return this.request('GET', this.indexPattern.getIndexForToday() + url).then(results => {
  62. results.data.$$config = results.config;
  63. return results.data;
  64. });
  65. }
  66. }
  67. private post(url, data) {
  68. return this.request('POST', url, data)
  69. .then(results => {
  70. results.data.$$config = results.config;
  71. return results.data;
  72. })
  73. .catch(err => {
  74. if (err.data && err.data.error) {
  75. throw {
  76. message: 'Elasticsearch error: ' + err.data.error.reason,
  77. error: err.data.error,
  78. };
  79. }
  80. throw err;
  81. });
  82. }
  83. annotationQuery(options) {
  84. const annotation = options.annotation;
  85. const timeField = annotation.timeField || '@timestamp';
  86. const queryString = annotation.query || '*';
  87. const tagsField = annotation.tagsField || 'tags';
  88. const textField = annotation.textField || null;
  89. const range = {};
  90. range[timeField] = {
  91. from: options.range.from.valueOf(),
  92. to: options.range.to.valueOf(),
  93. format: 'epoch_millis',
  94. };
  95. const queryInterpolated = this.templateSrv.replace(queryString, {}, 'lucene');
  96. const query = {
  97. bool: {
  98. filter: [
  99. { range: range },
  100. {
  101. query_string: {
  102. query: queryInterpolated,
  103. },
  104. },
  105. ],
  106. },
  107. };
  108. const data = {
  109. query: query,
  110. size: 10000,
  111. };
  112. // fields field not supported on ES 5.x
  113. if (this.esVersion < 5) {
  114. data['fields'] = [timeField, '_source'];
  115. }
  116. const header: any = {
  117. search_type: 'query_then_fetch',
  118. ignore_unavailable: true,
  119. };
  120. // old elastic annotations had index specified on them
  121. if (annotation.index) {
  122. header.index = annotation.index;
  123. } else {
  124. header.index = this.indexPattern.getIndexList(options.range.from, options.range.to);
  125. }
  126. const payload = angular.toJson(header) + '\n' + angular.toJson(data) + '\n';
  127. return this.post('_msearch', payload).then(res => {
  128. const list = [];
  129. const hits = res.responses[0].hits.hits;
  130. const getFieldFromSource = (source, fieldName) => {
  131. if (!fieldName) {
  132. return;
  133. }
  134. const fieldNames = fieldName.split('.');
  135. let fieldValue = source;
  136. for (let i = 0; i < fieldNames.length; i++) {
  137. fieldValue = fieldValue[fieldNames[i]];
  138. if (!fieldValue) {
  139. console.log('could not find field in annotation: ', fieldName);
  140. return '';
  141. }
  142. }
  143. return fieldValue;
  144. };
  145. for (let i = 0; i < hits.length; i++) {
  146. const source = hits[i]._source;
  147. let time = getFieldFromSource(source, timeField);
  148. if (typeof hits[i].fields !== 'undefined') {
  149. const fields = hits[i].fields;
  150. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  151. time = fields[timeField];
  152. }
  153. }
  154. const event = {
  155. annotation: annotation,
  156. time: toUtc(time).valueOf(),
  157. text: getFieldFromSource(source, textField),
  158. tags: getFieldFromSource(source, tagsField),
  159. };
  160. // legacy support for title tield
  161. if (annotation.titleField) {
  162. const title = getFieldFromSource(source, annotation.titleField);
  163. if (title) {
  164. event.text = title + '\n' + event.text;
  165. }
  166. }
  167. if (typeof event.tags === 'string') {
  168. event.tags = event.tags.split(',');
  169. }
  170. list.push(event);
  171. }
  172. return list;
  173. });
  174. }
  175. testDatasource() {
  176. this.timeSrv.setTime({ from: 'now-1m', to: 'now' }, true);
  177. // validate that the index exist and has date field
  178. return this.getFields({ type: 'date' }).then(
  179. dateFields => {
  180. const timeField: any = _.find(dateFields, { text: this.timeField });
  181. if (!timeField) {
  182. return {
  183. status: 'error',
  184. message: 'No date field named ' + this.timeField + ' found',
  185. };
  186. }
  187. return { status: 'success', message: 'Index OK. Time field name OK.' };
  188. },
  189. err => {
  190. console.log(err);
  191. if (err.data && err.data.error) {
  192. let message = angular.toJson(err.data.error);
  193. if (err.data.error.reason) {
  194. message = err.data.error.reason;
  195. }
  196. return { status: 'error', message: message };
  197. } else {
  198. return { status: 'error', message: err.status };
  199. }
  200. }
  201. );
  202. }
  203. getQueryHeader(searchType, timeFrom, timeTo) {
  204. const queryHeader: any = {
  205. search_type: searchType,
  206. ignore_unavailable: true,
  207. index: this.indexPattern.getIndexList(timeFrom, timeTo),
  208. };
  209. if (this.esVersion >= 56 && this.esVersion < 70) {
  210. queryHeader['max_concurrent_shard_requests'] = this.maxConcurrentShardRequests;
  211. }
  212. return angular.toJson(queryHeader);
  213. }
  214. query(options) {
  215. let payload = '';
  216. const targets = _.cloneDeep(options.targets);
  217. const sentTargets = [];
  218. // add global adhoc filters to timeFilter
  219. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  220. for (const target of targets) {
  221. if (target.hide) {
  222. continue;
  223. }
  224. if (target.alias) {
  225. target.alias = this.templateSrv.replace(target.alias, options.scopedVars, 'lucene');
  226. }
  227. const queryString = this.templateSrv.replace(target.query || '*', options.scopedVars, 'lucene');
  228. const queryObj = this.queryBuilder.build(target, adhocFilters, queryString);
  229. const esQuery = angular.toJson(queryObj);
  230. const searchType = queryObj.size === 0 && this.esVersion < 5 ? 'count' : 'query_then_fetch';
  231. const header = this.getQueryHeader(searchType, options.range.from, options.range.to);
  232. payload += header + '\n';
  233. payload += esQuery + '\n';
  234. sentTargets.push(target);
  235. }
  236. if (sentTargets.length === 0) {
  237. return this.$q.when([]);
  238. }
  239. payload = payload.replace(/\$timeFrom/g, options.range.from.valueOf());
  240. payload = payload.replace(/\$timeTo/g, options.range.to.valueOf());
  241. payload = this.templateSrv.replace(payload, options.scopedVars);
  242. const url = this.getMultiSearchUrl();
  243. return this.post(url, payload).then(res => {
  244. return new ElasticResponse(sentTargets, res).getTimeSeries();
  245. });
  246. }
  247. getFields(query) {
  248. const configuredEsVersion = this.esVersion;
  249. return this.get('/_mapping').then(result => {
  250. const typeMap = {
  251. float: 'number',
  252. double: 'number',
  253. integer: 'number',
  254. long: 'number',
  255. date: 'date',
  256. string: 'string',
  257. text: 'string',
  258. scaled_float: 'number',
  259. nested: 'nested',
  260. };
  261. function shouldAddField(obj, key, query) {
  262. if (key[0] === '_') {
  263. return false;
  264. }
  265. if (!query.type) {
  266. return true;
  267. }
  268. // equal query type filter, or via typemap translation
  269. return query.type === obj.type || query.type === typeMap[obj.type];
  270. }
  271. // Store subfield names: [system, process, cpu, total] -> system.process.cpu.total
  272. const fieldNameParts = [];
  273. const fields = {};
  274. function getFieldsRecursively(obj) {
  275. for (const key in obj) {
  276. const subObj = obj[key];
  277. // Check mapping field for nested fields
  278. if (_.isObject(subObj.properties)) {
  279. fieldNameParts.push(key);
  280. getFieldsRecursively(subObj.properties);
  281. }
  282. if (_.isObject(subObj.fields)) {
  283. fieldNameParts.push(key);
  284. getFieldsRecursively(subObj.fields);
  285. }
  286. if (_.isString(subObj.type)) {
  287. const fieldName = fieldNameParts.concat(key).join('.');
  288. // Hide meta-fields and check field type
  289. if (shouldAddField(subObj, key, query)) {
  290. fields[fieldName] = {
  291. text: fieldName,
  292. type: subObj.type,
  293. };
  294. }
  295. }
  296. }
  297. fieldNameParts.pop();
  298. }
  299. for (const indexName in result) {
  300. const index = result[indexName];
  301. if (index && index.mappings) {
  302. const mappings = index.mappings;
  303. if (configuredEsVersion < 70) {
  304. for (const typeName in mappings) {
  305. const properties = mappings[typeName].properties;
  306. getFieldsRecursively(properties);
  307. }
  308. } else {
  309. const properties = mappings.properties;
  310. getFieldsRecursively(properties);
  311. }
  312. }
  313. }
  314. // transform to array
  315. return _.map(fields, value => {
  316. return value;
  317. });
  318. });
  319. }
  320. getTerms(queryDef) {
  321. const range = this.timeSrv.timeRange();
  322. const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count';
  323. const header = this.getQueryHeader(searchType, range.from, range.to);
  324. let esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
  325. esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf());
  326. esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf());
  327. esQuery = header + '\n' + esQuery + '\n';
  328. const url = this.getMultiSearchUrl();
  329. return this.post(url, esQuery).then(res => {
  330. if (!res.responses[0].aggregations) {
  331. return [];
  332. }
  333. const buckets = res.responses[0].aggregations['1'].buckets;
  334. return _.map(buckets, bucket => {
  335. return {
  336. text: bucket.key_as_string || bucket.key,
  337. value: bucket.key,
  338. };
  339. });
  340. });
  341. }
  342. getMultiSearchUrl() {
  343. if (this.esVersion >= 70 && this.maxConcurrentShardRequests) {
  344. return `_msearch?max_concurrent_shard_requests=${this.maxConcurrentShardRequests}`;
  345. }
  346. return '_msearch';
  347. }
  348. metricFindQuery(query) {
  349. query = angular.fromJson(query);
  350. if (!query) {
  351. return this.$q.when([]);
  352. }
  353. if (query.find === 'fields') {
  354. query.field = this.templateSrv.replace(query.field, {}, 'lucene');
  355. return this.getFields(query);
  356. }
  357. if (query.find === 'terms') {
  358. query.field = this.templateSrv.replace(query.field, {}, 'lucene');
  359. query.query = this.templateSrv.replace(query.query || '*', {}, 'lucene');
  360. return this.getTerms(query);
  361. }
  362. }
  363. getTagKeys() {
  364. return this.getFields({});
  365. }
  366. getTagValues(options) {
  367. return this.getTerms({ field: options.key, query: '*' });
  368. }
  369. targetContainsTemplate(target) {
  370. if (this.templateSrv.variableExists(target.query) || this.templateSrv.variableExists(target.alias)) {
  371. return true;
  372. }
  373. for (const bucketAgg of target.bucketAggs) {
  374. if (this.templateSrv.variableExists(bucketAgg.field) || this.objectContainsTemplate(bucketAgg.settings)) {
  375. return true;
  376. }
  377. }
  378. for (const metric of target.metrics) {
  379. if (
  380. this.templateSrv.variableExists(metric.field) ||
  381. this.objectContainsTemplate(metric.settings) ||
  382. this.objectContainsTemplate(metric.meta)
  383. ) {
  384. return true;
  385. }
  386. }
  387. return false;
  388. }
  389. private isPrimitive(obj) {
  390. if (obj === null || obj === undefined) {
  391. return true;
  392. }
  393. if (['string', 'number', 'boolean'].some(type => type === typeof true)) {
  394. return true;
  395. }
  396. return false;
  397. }
  398. private objectContainsTemplate(obj) {
  399. if (!obj) {
  400. return false;
  401. }
  402. for (const key of Object.keys(obj)) {
  403. if (this.isPrimitive(obj[key])) {
  404. if (this.templateSrv.variableExists(obj[key])) {
  405. return true;
  406. }
  407. } else if (Array.isArray(obj[key])) {
  408. for (const item of obj[key]) {
  409. if (this.objectContainsTemplate(item)) {
  410. return true;
  411. }
  412. }
  413. } else {
  414. if (this.objectContainsTemplate(obj[key])) {
  415. return true;
  416. }
  417. }
  418. }
  419. return false;
  420. }
  421. }