datasource.js 13 KB

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