datasource.js 13 KB

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