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