datasource.js 11 KB

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