datasource.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'app/core/utils/datemath',
  5. 'moment',
  6. ],
  7. function (angular, _, dateMath) {
  8. 'use strict';
  9. /** @ngInject */
  10. function OpenTsDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  11. this.type = 'opentsdb';
  12. this.url = instanceSettings.url;
  13. this.name = instanceSettings.name;
  14. this.withCredentials = instanceSettings.withCredentials;
  15. this.basicAuth = instanceSettings.basicAuth;
  16. instanceSettings.jsonData = instanceSettings.jsonData || {};
  17. this.tsdbVersion = instanceSettings.jsonData.tsdbVersion || 1;
  18. this.tsdbResolution = instanceSettings.jsonData.tsdbResolution || 1;
  19. this.supportMetrics = true;
  20. this.tagKeys = {};
  21. // Called once per panel (graph)
  22. this.query = function(options) {
  23. var start = convertToTSDBTime(options.rangeRaw.from, false);
  24. var end = convertToTSDBTime(options.rangeRaw.to, true);
  25. var qs = [];
  26. _.each(options.targets, function(target) {
  27. if (!target.metric) { return; }
  28. qs.push(convertTargetToQuery(target, options, this.tsdbVersion));
  29. }.bind(this));
  30. var queries = _.compact(qs);
  31. // No valid targets, return the empty result to save a round trip.
  32. if (_.isEmpty(queries)) {
  33. var d = $q.defer();
  34. d.resolve({ data: [] });
  35. return d.promise;
  36. }
  37. var groupByTags = {};
  38. _.each(queries, function(query) {
  39. if (query.filters && query.filters.length > 0) {
  40. _.each(query.filters, function(val) {
  41. groupByTags[val.tagk] = true;
  42. });
  43. } else {
  44. _.each(query.tags, function(val, key) {
  45. groupByTags[key] = true;
  46. });
  47. }
  48. });
  49. options.targets = _.filter(options.targets, function(query) {
  50. return query.hide !== true;
  51. });
  52. return this.performTimeSeriesQuery(queries, start, end).then(function(response) {
  53. var metricToTargetMapping = mapMetricsToTargets(response.data, options, this.tsdbVersion);
  54. var result = _.map(response.data, function(metricData, index) {
  55. index = metricToTargetMapping[index];
  56. if (index === -1) {
  57. index = 0;
  58. }
  59. this._saveTagKeys(metricData);
  60. return transformMetricData(metricData, groupByTags, options.targets[index], options, this.tsdbResolution);
  61. }.bind(this));
  62. return { data: result };
  63. }.bind(this));
  64. };
  65. this.annotationQuery = function(options) {
  66. var start = convertToTSDBTime(options.rangeRaw.from, false);
  67. var end = convertToTSDBTime(options.rangeRaw.to, true);
  68. var qs = [];
  69. var eventList = [];
  70. qs.push({ aggregator:"sum", metric:options.annotation.target });
  71. var queries = _.compact(qs);
  72. return this.performTimeSeriesQuery(queries, start, end).then(function(results) {
  73. if(results.data[0]) {
  74. var annotationObject = results.data[0].annotations;
  75. if(options.annotation.isGlobal){
  76. annotationObject = results.data[0].globalAnnotations;
  77. }
  78. if(annotationObject) {
  79. _.each(annotationObject, function(annotation) {
  80. var event = {
  81. text: annotation.description,
  82. time: Math.floor(annotation.startTime) * 1000,
  83. annotation: options.annotation
  84. };
  85. eventList.push(event);
  86. });
  87. }
  88. }
  89. return eventList;
  90. }.bind(this));
  91. };
  92. this.targetContainsTemplate = function(target) {
  93. if (target.filters && target.filters.length > 0) {
  94. for (var i = 0; i < target.filters.length; i++) {
  95. if (templateSrv.variableExists(target.filters[i].filter)) {
  96. return true;
  97. }
  98. }
  99. }
  100. if (target.tags && Object.keys(target.tags).length > 0) {
  101. for (var tagKey in target.tags) {
  102. if (templateSrv.variableExists(target.tags[tagKey])) {
  103. return true;
  104. }
  105. }
  106. }
  107. return false;
  108. };
  109. this.performTimeSeriesQuery = function(queries, start, end) {
  110. var msResolution = false;
  111. if (this.tsdbResolution === 2) {
  112. msResolution = true;
  113. }
  114. var reqBody = {
  115. start: start,
  116. queries: queries,
  117. msResolution: msResolution,
  118. globalAnnotations: true
  119. };
  120. if (this.tsdbVersion === 3) {
  121. reqBody.showQuery = true;
  122. }
  123. // Relative queries (e.g. last hour) don't include an end time
  124. if (end) {
  125. reqBody.end = end;
  126. }
  127. var options = {
  128. method: 'POST',
  129. url: this.url + '/api/query',
  130. data: reqBody
  131. };
  132. this._addCredentialOptions(options);
  133. return backendSrv.datasourceRequest(options);
  134. };
  135. this.suggestTagKeys = function(metric) {
  136. return $q.when(this.tagKeys[metric] || []);
  137. };
  138. this._saveTagKeys = function(metricData) {
  139. var tagKeys = Object.keys(metricData.tags);
  140. _.each(metricData.aggregateTags, function(tag) {
  141. tagKeys.push(tag);
  142. });
  143. this.tagKeys[metricData.metric] = tagKeys;
  144. };
  145. this._performSuggestQuery = function(query, type) {
  146. return this._get('/api/suggest', {type: type, q: query, max: 1000}).then(function(result) {
  147. return result.data;
  148. });
  149. };
  150. this._performMetricKeyValueLookup = function(metric, keys) {
  151. if(!metric || !keys) {
  152. return $q.when([]);
  153. }
  154. var keysArray = keys.split(",").map(function(key) {
  155. return key.trim();
  156. });
  157. var key = keysArray[0];
  158. var keysQuery = key + "=*";
  159. if (keysArray.length > 1) {
  160. keysQuery += "," + keysArray.splice(1).join(",");
  161. }
  162. var m = metric + "{" + keysQuery + "}";
  163. return this._get('/api/search/lookup', {m: m, limit: 3000}).then(function(result) {
  164. result = result.data.results;
  165. var tagvs = [];
  166. _.each(result, function(r) {
  167. if (tagvs.indexOf(r.tags[key]) === -1) {
  168. tagvs.push(r.tags[key]);
  169. }
  170. });
  171. return tagvs;
  172. });
  173. };
  174. this._performMetricKeyLookup = function(metric) {
  175. if(!metric) { return $q.when([]); }
  176. return this._get('/api/search/lookup', {m: metric, limit: 1000}).then(function(result) {
  177. result = result.data.results;
  178. var tagks = [];
  179. _.each(result, function(r) {
  180. _.each(r.tags, function(tagv, tagk) {
  181. if(tagks.indexOf(tagk) === -1) {
  182. tagks.push(tagk);
  183. }
  184. });
  185. });
  186. return tagks;
  187. });
  188. };
  189. this._get = function(relativeUrl, params) {
  190. var options = {
  191. method: 'GET',
  192. url: this.url + relativeUrl,
  193. params: params,
  194. };
  195. this._addCredentialOptions(options);
  196. return backendSrv.datasourceRequest(options);
  197. };
  198. this._addCredentialOptions = function(options) {
  199. if (this.basicAuth || this.withCredentials) {
  200. options.withCredentials = true;
  201. }
  202. if (this.basicAuth) {
  203. options.headers = {"Authorization": this.basicAuth};
  204. }
  205. };
  206. this.metricFindQuery = function(query) {
  207. if (!query) { return $q.when([]); }
  208. var interpolated;
  209. try {
  210. interpolated = templateSrv.replace(query, {}, 'distributed');
  211. }
  212. catch (err) {
  213. return $q.reject(err);
  214. }
  215. var responseTransform = function(result) {
  216. return _.map(result, function(value) {
  217. return {text: value};
  218. });
  219. };
  220. var metrics_regex = /metrics\((.*)\)/;
  221. var tag_names_regex = /tag_names\((.*)\)/;
  222. var tag_values_regex = /tag_values\((.*?),\s?(.*)\)/;
  223. var tag_names_suggest_regex = /suggest_tagk\((.*)\)/;
  224. var tag_values_suggest_regex = /suggest_tagv\((.*)\)/;
  225. var metrics_query = interpolated.match(metrics_regex);
  226. if (metrics_query) {
  227. return this._performSuggestQuery(metrics_query[1], 'metrics').then(responseTransform);
  228. }
  229. var tag_names_query = interpolated.match(tag_names_regex);
  230. if (tag_names_query) {
  231. return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform);
  232. }
  233. var tag_values_query = interpolated.match(tag_values_regex);
  234. if (tag_values_query) {
  235. return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2]).then(responseTransform);
  236. }
  237. var tag_names_suggest_query = interpolated.match(tag_names_suggest_regex);
  238. if (tag_names_suggest_query) {
  239. return this._performSuggestQuery(tag_names_suggest_query[1], 'tagk').then(responseTransform);
  240. }
  241. var tag_values_suggest_query = interpolated.match(tag_values_suggest_regex);
  242. if (tag_values_suggest_query) {
  243. return this._performSuggestQuery(tag_values_suggest_query[1], 'tagv').then(responseTransform);
  244. }
  245. return $q.when([]);
  246. };
  247. this.testDatasource = function() {
  248. return this._performSuggestQuery('cpu', 'metrics').then(function () {
  249. return { status: "success", message: "Data source is working" };
  250. });
  251. };
  252. var aggregatorsPromise = null;
  253. this.getAggregators = function() {
  254. if (aggregatorsPromise) { return aggregatorsPromise; }
  255. aggregatorsPromise = this._get('/api/aggregators').then(function(result) {
  256. if (result.data && _.isArray(result.data)) {
  257. return result.data.sort();
  258. }
  259. return [];
  260. });
  261. return aggregatorsPromise;
  262. };
  263. var filterTypesPromise = null;
  264. this.getFilterTypes = function() {
  265. if (filterTypesPromise) { return filterTypesPromise; }
  266. filterTypesPromise = this._get('/api/config/filters').then(function(result) {
  267. if (result.data) {
  268. return Object.keys(result.data).sort();
  269. }
  270. return [];
  271. });
  272. return filterTypesPromise;
  273. };
  274. function transformMetricData(md, groupByTags, target, options, tsdbResolution) {
  275. var metricLabel = createMetricLabel(md, target, groupByTags, options);
  276. var dps = [];
  277. // TSDB returns datapoints has a hash of ts => value.
  278. // Can't use _.pairs(invert()) because it stringifies keys/values
  279. _.each(md.dps, function (v, k) {
  280. if (tsdbResolution === 2) {
  281. dps.push([v, k * 1]);
  282. } else {
  283. dps.push([v, k * 1000]);
  284. }
  285. });
  286. return { target: metricLabel, datapoints: dps };
  287. }
  288. function createMetricLabel(md, target, groupByTags, options) {
  289. if (target.alias) {
  290. var scopedVars = _.clone(options.scopedVars || {});
  291. _.each(md.tags, function(value, key) {
  292. scopedVars['tag_' + key] = {value: value};
  293. });
  294. return templateSrv.replace(target.alias, scopedVars);
  295. }
  296. var label = md.metric;
  297. var tagData = [];
  298. if (!_.isEmpty(md.tags)) {
  299. _.each(_.toPairs(md.tags), function(tag) {
  300. if (_.has(groupByTags, tag[0])) {
  301. tagData.push(tag[0] + "=" + tag[1]);
  302. }
  303. });
  304. }
  305. if (!_.isEmpty(tagData)) {
  306. label += "{" + tagData.join(", ") + "}";
  307. }
  308. return label;
  309. }
  310. function convertTargetToQuery(target, options, tsdbVersion) {
  311. if (!target.metric || target.hide) {
  312. return null;
  313. }
  314. var query = {
  315. metric: templateSrv.replace(target.metric, options.scopedVars, 'pipe'),
  316. aggregator: "avg"
  317. };
  318. if (target.aggregator) {
  319. query.aggregator = templateSrv.replace(target.aggregator);
  320. }
  321. if (target.shouldComputeRate) {
  322. query.rate = true;
  323. query.rateOptions = {
  324. counter: !!target.isCounter
  325. };
  326. if (target.counterMax && target.counterMax.length) {
  327. query.rateOptions.counterMax = parseInt(target.counterMax);
  328. }
  329. if (target.counterResetValue && target.counterResetValue.length) {
  330. query.rateOptions.resetValue = parseInt(target.counterResetValue);
  331. }
  332. if(tsdbVersion >= 2) {
  333. query.rateOptions.dropResets = !query.rateOptions.counterMax &&
  334. (!query.rateOptions.ResetValue || query.rateOptions.ResetValue === 0);
  335. }
  336. }
  337. if (!target.disableDownsampling) {
  338. var interval = templateSrv.replace(target.downsampleInterval || options.interval);
  339. if (interval.match(/\.[0-9]+s/)) {
  340. interval = parseFloat(interval)*1000 + "ms";
  341. }
  342. query.downsample = interval + "-" + target.downsampleAggregator;
  343. if (target.downsampleFillPolicy && target.downsampleFillPolicy !== "none") {
  344. query.downsample += "-" + target.downsampleFillPolicy;
  345. }
  346. }
  347. if (target.filters && target.filters.length > 0) {
  348. query.filters = angular.copy(target.filters);
  349. if (query.filters){
  350. for (var filter_key in query.filters) {
  351. query.filters[filter_key].filter = templateSrv.replace(query.filters[filter_key].filter, options.scopedVars, 'pipe');
  352. }
  353. }
  354. } else {
  355. query.tags = angular.copy(target.tags);
  356. if (query.tags){
  357. for (var tag_key in query.tags) {
  358. query.tags[tag_key] = templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe');
  359. }
  360. }
  361. }
  362. if (target.explicitTags) {
  363. query.explicitTags = true;
  364. }
  365. return query;
  366. }
  367. function mapMetricsToTargets(metrics, options, tsdbVersion) {
  368. var interpolatedTagValue, arrTagV;
  369. return _.map(metrics, function(metricData) {
  370. if (tsdbVersion === 3) {
  371. return metricData.query.index;
  372. } else {
  373. return _.findIndex(options.targets, function(target) {
  374. if (target.filters && target.filters.length > 0) {
  375. return target.metric === metricData.metric;
  376. } else {
  377. return target.metric === metricData.metric &&
  378. _.every(target.tags, function(tagV, tagK) {
  379. interpolatedTagValue = templateSrv.replace(tagV, options.scopedVars, 'pipe');
  380. arrTagV = interpolatedTagValue.split('|');
  381. return _.includes(arrTagV, metricData.tags[tagK]) || interpolatedTagValue === "*";
  382. });
  383. }
  384. });
  385. }
  386. });
  387. }
  388. function convertToTSDBTime(date, roundUp) {
  389. if (date === 'now') {
  390. return null;
  391. }
  392. date = dateMath.parse(date, roundUp);
  393. return date.valueOf();
  394. }
  395. }
  396. return OpenTsDatasource;
  397. });