datasource.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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));
  29. });
  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. return this.performTimeSeriesQuery(queries, start, end).then(function(response) {
  50. var metricToTargetMapping = mapMetricsToTargets(response.data, options);
  51. var result = _.map(response.data, function(metricData, index) {
  52. index = metricToTargetMapping[index];
  53. if (index === -1) {
  54. index = 0;
  55. }
  56. this._saveTagKeys(metricData);
  57. return transformMetricData(metricData, groupByTags, options.targets[index], options, this.tsdbResolution);
  58. }.bind(this));
  59. return { data: result };
  60. }.bind(this));
  61. };
  62. this.performTimeSeriesQuery = function(queries, start, end) {
  63. var msResolution = false;
  64. if (this.tsdbResolution === 2) {
  65. msResolution = true;
  66. }
  67. var reqBody = {
  68. start: start,
  69. queries: queries,
  70. msResolution: msResolution
  71. };
  72. // Relative queries (e.g. last hour) don't include an end time
  73. if (end) {
  74. reqBody.end = end;
  75. }
  76. var options = {
  77. method: 'POST',
  78. url: this.url + '/api/query',
  79. data: reqBody
  80. };
  81. if (this.basicAuth || this.withCredentials) {
  82. options.withCredentials = true;
  83. }
  84. if (this.basicAuth) {
  85. options.headers = {"Authorization": this.basicAuth};
  86. }
  87. // In case the backend is 3rd-party hosted and does not suport OPTIONS, urlencoded requests
  88. // go as POST rather than OPTIONS+POST
  89. options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
  90. return backendSrv.datasourceRequest(options);
  91. };
  92. this.suggestTagKeys = function(metric) {
  93. return $q.when(this.tagKeys[metric] || []);
  94. };
  95. this._saveTagKeys = function(metricData) {
  96. var tagKeys = Object.keys(metricData.tags);
  97. _.each(metricData.aggregateTags, function(tag) {
  98. tagKeys.push(tag);
  99. });
  100. this.tagKeys[metricData.metric] = tagKeys;
  101. };
  102. this._performSuggestQuery = function(query, type) {
  103. return this._get('/api/suggest', {type: type, q: query, max: 1000}).then(function(result) {
  104. return result.data;
  105. });
  106. };
  107. this._performMetricKeyValueLookup = function(metric, key) {
  108. if(!metric || !key) {
  109. return $q.when([]);
  110. }
  111. var m = metric + "{" + key + "=*}";
  112. return this._get('/api/search/lookup', {m: m, limit: 3000}).then(function(result) {
  113. result = result.data.results;
  114. var tagvs = [];
  115. _.each(result, function(r) {
  116. if (tagvs.indexOf(r.tags[key]) === -1) {
  117. tagvs.push(r.tags[key]);
  118. }
  119. });
  120. return tagvs;
  121. });
  122. };
  123. this._performMetricKeyLookup = function(metric) {
  124. if(!metric) { return $q.when([]); }
  125. return this._get('/api/search/lookup', {m: metric, limit: 1000}).then(function(result) {
  126. result = result.data.results;
  127. var tagks = [];
  128. _.each(result, function(r) {
  129. _.each(r.tags, function(tagv, tagk) {
  130. if(tagks.indexOf(tagk) === -1) {
  131. tagks.push(tagk);
  132. }
  133. });
  134. });
  135. return tagks;
  136. });
  137. };
  138. this._get = function(relativeUrl, params) {
  139. return backendSrv.datasourceRequest({
  140. method: 'GET',
  141. url: this.url + relativeUrl,
  142. params: params,
  143. });
  144. };
  145. this.metricFindQuery = function(query) {
  146. if (!query) { return $q.when([]); }
  147. var interpolated;
  148. try {
  149. interpolated = templateSrv.replace(query);
  150. }
  151. catch (err) {
  152. return $q.reject(err);
  153. }
  154. var responseTransform = function(result) {
  155. return _.map(result, function(value) {
  156. return {text: value};
  157. });
  158. };
  159. var metrics_regex = /metrics\((.*)\)/;
  160. var tag_names_regex = /tag_names\((.*)\)/;
  161. var tag_values_regex = /tag_values\((.*),\s?(.*)\)/;
  162. var tag_names_suggest_regex = /suggest_tagk\((.*)\)/;
  163. var tag_values_suggest_regex = /suggest_tagv\((.*)\)/;
  164. var metrics_query = interpolated.match(metrics_regex);
  165. if (metrics_query) {
  166. return this._performSuggestQuery(metrics_query[1], 'metrics').then(responseTransform);
  167. }
  168. var tag_names_query = interpolated.match(tag_names_regex);
  169. if (tag_names_query) {
  170. return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform);
  171. }
  172. var tag_values_query = interpolated.match(tag_values_regex);
  173. if (tag_values_query) {
  174. return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2]).then(responseTransform);
  175. }
  176. var tag_names_suggest_query = interpolated.match(tag_names_suggest_regex);
  177. if (tag_names_suggest_query) {
  178. return this._performSuggestQuery(tag_names_suggest_query[1], 'tagk').then(responseTransform);
  179. }
  180. var tag_values_suggest_query = interpolated.match(tag_values_suggest_regex);
  181. if (tag_values_suggest_query) {
  182. return this._performSuggestQuery(tag_values_suggest_query[1], 'tagv').then(responseTransform);
  183. }
  184. return $q.when([]);
  185. };
  186. this.testDatasource = function() {
  187. return this._performSuggestQuery('cpu', 'metrics').then(function () {
  188. return { status: "success", message: "Data source is working", title: "Success" };
  189. });
  190. };
  191. var aggregatorsPromise = null;
  192. this.getAggregators = function() {
  193. if (aggregatorsPromise) { return aggregatorsPromise; }
  194. aggregatorsPromise = this._get('/api/aggregators').then(function(result) {
  195. if (result.data && _.isArray(result.data)) {
  196. return result.data.sort();
  197. }
  198. return [];
  199. });
  200. return aggregatorsPromise;
  201. };
  202. var filterTypesPromise = null;
  203. this.getFilterTypes = function() {
  204. if (filterTypesPromise) { return filterTypesPromise; }
  205. filterTypesPromise = this._get('/api/config/filters').then(function(result) {
  206. if (result.data) {
  207. return Object.keys(result.data).sort();
  208. }
  209. return [];
  210. });
  211. return filterTypesPromise;
  212. };
  213. function transformMetricData(md, groupByTags, target, options, tsdbResolution) {
  214. var metricLabel = createMetricLabel(md, target, groupByTags, options);
  215. var dps = [];
  216. // TSDB returns datapoints has a hash of ts => value.
  217. // Can't use _.pairs(invert()) because it stringifies keys/values
  218. _.each(md.dps, function (v, k) {
  219. if (tsdbResolution === 2) {
  220. dps.push([v, k * 1]);
  221. } else {
  222. dps.push([v, k * 1000]);
  223. }
  224. });
  225. return { target: metricLabel, datapoints: dps };
  226. }
  227. function createMetricLabel(md, target, groupByTags, options) {
  228. if (target.alias) {
  229. var scopedVars = _.clone(options.scopedVars || {});
  230. _.each(md.tags, function(value, key) {
  231. scopedVars['tag_' + key] = {value: value};
  232. });
  233. return templateSrv.replace(target.alias, scopedVars);
  234. }
  235. var label = md.metric;
  236. var tagData = [];
  237. if (!_.isEmpty(md.tags)) {
  238. _.each(_.pairs(md.tags), function(tag) {
  239. if (_.has(groupByTags, tag[0])) {
  240. tagData.push(tag[0] + "=" + tag[1]);
  241. }
  242. });
  243. }
  244. if (!_.isEmpty(tagData)) {
  245. label += "{" + tagData.join(", ") + "}";
  246. }
  247. return label;
  248. }
  249. function convertTargetToQuery(target, options) {
  250. if (!target.metric || target.hide) {
  251. return null;
  252. }
  253. var query = {
  254. metric: templateSrv.replace(target.metric, options.scopedVars),
  255. aggregator: "avg"
  256. };
  257. if (target.aggregator) {
  258. query.aggregator = templateSrv.replace(target.aggregator);
  259. }
  260. if (target.shouldComputeRate) {
  261. query.rate = true;
  262. query.rateOptions = {
  263. counter: !!target.isCounter
  264. };
  265. if (target.counterMax && target.counterMax.length) {
  266. query.rateOptions.counterMax = parseInt(target.counterMax);
  267. }
  268. if (target.counterResetValue && target.counterResetValue.length) {
  269. query.rateOptions.resetValue = parseInt(target.counterResetValue);
  270. }
  271. }
  272. if (!target.disableDownsampling) {
  273. var interval = templateSrv.replace(target.downsampleInterval || options.interval);
  274. if (interval.match(/\.[0-9]+s/)) {
  275. interval = parseFloat(interval)*1000 + "ms";
  276. }
  277. query.downsample = interval + "-" + target.downsampleAggregator;
  278. if (target.downsampleFillPolicy && target.downsampleFillPolicy !== "none") {
  279. query.downsample += "-" + target.downsampleFillPolicy;
  280. }
  281. }
  282. if (target.filters && target.filters.length > 0) {
  283. query.filters = angular.copy(target.filters);
  284. } else {
  285. query.tags = angular.copy(target.tags);
  286. if(query.tags){
  287. for(var key in query.tags){
  288. query.tags[key] = templateSrv.replace(query.tags[key], options.scopedVars, 'pipe');
  289. }
  290. }
  291. }
  292. return query;
  293. }
  294. function mapMetricsToTargets(metrics, options) {
  295. var interpolatedTagValue;
  296. return _.map(metrics, function(metricData) {
  297. return _.findIndex(options.targets, function(target) {
  298. if (target.filters && target.filters.length > 0) {
  299. return target.metric === metricData.metric &&
  300. _.all(target.filters, function(filter) {
  301. return filter.tagk === interpolatedTagValue === "*";
  302. });
  303. } else {
  304. return target.metric === metricData.metric &&
  305. _.all(target.tags, function(tagV, tagK) {
  306. interpolatedTagValue = templateSrv.replace(tagV, options.scopedVars, 'pipe');
  307. return metricData.tags[tagK] === interpolatedTagValue || interpolatedTagValue === "*";
  308. });
  309. }
  310. });
  311. });
  312. }
  313. function convertToTSDBTime(date, roundUp) {
  314. if (date === 'now') {
  315. return null;
  316. }
  317. date = dateMath.parse(date, roundUp);
  318. return date.valueOf();
  319. }
  320. }
  321. return {
  322. OpenTsDatasource: OpenTsDatasource
  323. };
  324. });