datasource.ts 13 KB

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