datasource.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. let queryString = this.templateSrv.replace(target.query, options.scopedVars, 'lucene');
  228. // Elasticsearch queryString should always be '*' if empty string
  229. if (!queryString || queryString === '') {
  230. queryString = '*';
  231. }
  232. const queryObj = this.queryBuilder.build(target, adhocFilters, queryString);
  233. const esQuery = angular.toJson(queryObj);
  234. const searchType = queryObj.size === 0 && this.esVersion < 5 ? 'count' : 'query_then_fetch';
  235. const header = this.getQueryHeader(searchType, options.range.from, options.range.to);
  236. payload += header + '\n';
  237. payload += esQuery + '\n';
  238. sentTargets.push(target);
  239. }
  240. if (sentTargets.length === 0) {
  241. return this.$q.when([]);
  242. }
  243. payload = payload.replace(/\$timeFrom/g, options.range.from.valueOf());
  244. payload = payload.replace(/\$timeTo/g, options.range.to.valueOf());
  245. payload = this.templateSrv.replace(payload, options.scopedVars);
  246. const url = this.getMultiSearchUrl();
  247. return this.post(url, payload).then(res => {
  248. return new ElasticResponse(sentTargets, res).getTimeSeries();
  249. });
  250. }
  251. getFields(query) {
  252. const configuredEsVersion = this.esVersion;
  253. return this.get('/_mapping').then(result => {
  254. const typeMap = {
  255. float: 'number',
  256. double: 'number',
  257. integer: 'number',
  258. long: 'number',
  259. date: 'date',
  260. string: 'string',
  261. text: 'string',
  262. scaled_float: 'number',
  263. nested: 'nested',
  264. };
  265. function shouldAddField(obj, key, query) {
  266. if (key[0] === '_') {
  267. return false;
  268. }
  269. if (!query.type) {
  270. return true;
  271. }
  272. // equal query type filter, or via typemap translation
  273. return query.type === obj.type || query.type === typeMap[obj.type];
  274. }
  275. // Store subfield names: [system, process, cpu, total] -> system.process.cpu.total
  276. const fieldNameParts = [];
  277. const fields = {};
  278. function getFieldsRecursively(obj) {
  279. for (const key in obj) {
  280. const subObj = obj[key];
  281. // Check mapping field for nested fields
  282. if (_.isObject(subObj.properties)) {
  283. fieldNameParts.push(key);
  284. getFieldsRecursively(subObj.properties);
  285. }
  286. if (_.isObject(subObj.fields)) {
  287. fieldNameParts.push(key);
  288. getFieldsRecursively(subObj.fields);
  289. }
  290. if (_.isString(subObj.type)) {
  291. const fieldName = fieldNameParts.concat(key).join('.');
  292. // Hide meta-fields and check field type
  293. if (shouldAddField(subObj, key, query)) {
  294. fields[fieldName] = {
  295. text: fieldName,
  296. type: subObj.type,
  297. };
  298. }
  299. }
  300. }
  301. fieldNameParts.pop();
  302. }
  303. for (const indexName in result) {
  304. const index = result[indexName];
  305. if (index && index.mappings) {
  306. const mappings = index.mappings;
  307. if (configuredEsVersion < 70) {
  308. for (const typeName in mappings) {
  309. const properties = mappings[typeName].properties;
  310. getFieldsRecursively(properties);
  311. }
  312. } else {
  313. const properties = mappings.properties;
  314. getFieldsRecursively(properties);
  315. }
  316. }
  317. }
  318. // transform to array
  319. return _.map(fields, value => {
  320. return value;
  321. });
  322. });
  323. }
  324. getTerms(queryDef) {
  325. const range = this.timeSrv.timeRange();
  326. const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count';
  327. const header = this.getQueryHeader(searchType, range.from, range.to);
  328. let esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
  329. esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf());
  330. esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf());
  331. esQuery = header + '\n' + esQuery + '\n';
  332. const url = this.getMultiSearchUrl();
  333. return this.post(url, esQuery).then(res => {
  334. if (!res.responses[0].aggregations) {
  335. return [];
  336. }
  337. const buckets = res.responses[0].aggregations['1'].buckets;
  338. return _.map(buckets, bucket => {
  339. return {
  340. text: bucket.key_as_string || bucket.key,
  341. value: bucket.key,
  342. };
  343. });
  344. });
  345. }
  346. getMultiSearchUrl() {
  347. if (this.esVersion >= 70 && this.maxConcurrentShardRequests) {
  348. return `_msearch?max_concurrent_shard_requests=${this.maxConcurrentShardRequests}`;
  349. }
  350. return '_msearch';
  351. }
  352. metricFindQuery(query) {
  353. query = angular.fromJson(query);
  354. if (!query) {
  355. return this.$q.when([]);
  356. }
  357. if (query.find === 'fields') {
  358. query.field = this.templateSrv.replace(query.field, {}, 'lucene');
  359. return this.getFields(query);
  360. }
  361. if (query.find === 'terms') {
  362. query.field = this.templateSrv.replace(query.field, {}, 'lucene');
  363. query.query = this.templateSrv.replace(query.query || '*', {}, 'lucene');
  364. return this.getTerms(query);
  365. }
  366. }
  367. getTagKeys() {
  368. return this.getFields({});
  369. }
  370. getTagValues(options) {
  371. return this.getTerms({ field: options.key, query: '*' });
  372. }
  373. targetContainsTemplate(target) {
  374. if (this.templateSrv.variableExists(target.query) || this.templateSrv.variableExists(target.alias)) {
  375. return true;
  376. }
  377. for (const bucketAgg of target.bucketAggs) {
  378. if (this.templateSrv.variableExists(bucketAgg.field) || this.objectContainsTemplate(bucketAgg.settings)) {
  379. return true;
  380. }
  381. }
  382. for (const metric of target.metrics) {
  383. if (
  384. this.templateSrv.variableExists(metric.field) ||
  385. this.objectContainsTemplate(metric.settings) ||
  386. this.objectContainsTemplate(metric.meta)
  387. ) {
  388. return true;
  389. }
  390. }
  391. return false;
  392. }
  393. private isPrimitive(obj) {
  394. if (obj === null || obj === undefined) {
  395. return true;
  396. }
  397. if (['string', 'number', 'boolean'].some(type => type === typeof true)) {
  398. return true;
  399. }
  400. return false;
  401. }
  402. private objectContainsTemplate(obj) {
  403. if (!obj) {
  404. return false;
  405. }
  406. for (const key of Object.keys(obj)) {
  407. if (this.isPrimitive(obj[key])) {
  408. if (this.templateSrv.variableExists(obj[key])) {
  409. return true;
  410. }
  411. } else if (Array.isArray(obj[key])) {
  412. for (const item of obj[key]) {
  413. if (this.objectContainsTemplate(item)) {
  414. return true;
  415. }
  416. }
  417. } else {
  418. if (this.objectContainsTemplate(obj[key])) {
  419. return true;
  420. }
  421. }
  422. }
  423. return false;
  424. }
  425. }