datasource.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import moment from 'moment';
  5. import kbn from 'app/core/utils/kbn';
  6. import * as dateMath from 'app/core/utils/datemath';
  7. import PrometheusMetricFindQuery from './metric_find_query';
  8. var durationSplitRegexp = /(\d+)(ms|s|m|h|d|w|M|y)/;
  9. /** @ngInject */
  10. export function PrometheusDatasource(instanceSettings, $q, backendSrv, templateSrv, timeSrv) {
  11. this.type = 'prometheus';
  12. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  13. this.name = instanceSettings.name;
  14. this.supportMetrics = true;
  15. this.url = instanceSettings.url;
  16. this.directUrl = instanceSettings.directUrl;
  17. this.basicAuth = instanceSettings.basicAuth;
  18. this.withCredentials = instanceSettings.withCredentials;
  19. this.lastErrors = {};
  20. this._request = function(method, url, requestId) {
  21. var options: any = {
  22. url: this.url + url,
  23. method: method,
  24. requestId: requestId,
  25. };
  26. if (this.basicAuth || this.withCredentials) {
  27. options.withCredentials = true;
  28. }
  29. if (this.basicAuth) {
  30. options.headers = {
  31. "Authorization": this.basicAuth
  32. };
  33. }
  34. return backendSrv.datasourceRequest(options);
  35. };
  36. function prometheusSpecialRegexEscape(value) {
  37. return value.replace(/[\\^$*+?.()|[\]{}]/g, '\\\\$&');
  38. }
  39. this.interpolateQueryExpr = function(value, variable, defaultFormatFn) {
  40. // if no multi or include all do not regexEscape
  41. if (!variable.multi && !variable.includeAll) {
  42. return value;
  43. }
  44. if (typeof value === 'string') {
  45. return prometheusSpecialRegexEscape(value);
  46. }
  47. var escapedValues = _.map(value, prometheusSpecialRegexEscape);
  48. return escapedValues.join('|');
  49. };
  50. this.targetContainsTemplate = function(target) {
  51. return templateSrv.variableExists(target.expr);
  52. };
  53. // Called once per panel (graph)
  54. this.query = function(options) {
  55. var self = this;
  56. var start = this.getPrometheusTime(options.range.from, false);
  57. var end = this.getPrometheusTime(options.range.to, true);
  58. var queries = [];
  59. var activeTargets = [];
  60. options = _.clone(options);
  61. _.each(options.targets, target => {
  62. if (!target.expr || target.hide) {
  63. return;
  64. }
  65. activeTargets.push(target);
  66. var query: any = {};
  67. query.expr = templateSrv.replace(target.expr, options.scopedVars, self.interpolateQueryExpr);
  68. query.requestId = options.panelId + target.refId;
  69. var interval = templateSrv.replace(target.interval, options.scopedVars) || options.interval;
  70. var intervalFactor = target.intervalFactor || 1;
  71. target.step = query.step = this.calculateInterval(interval, intervalFactor);
  72. var range = Math.ceil(end - start);
  73. target.step = query.step = this.adjustStep(query.step, this.intervalSeconds(options.interval), range);
  74. queries.push(query);
  75. });
  76. // No valid targets, return the empty result to save a round trip.
  77. if (_.isEmpty(queries)) {
  78. var d = $q.defer();
  79. d.resolve({ data: [] });
  80. return d.promise;
  81. }
  82. var allQueryPromise = _.map(queries, query => {
  83. return this.performTimeSeriesQuery(query, start, end);
  84. });
  85. return $q.all(allQueryPromise).then(function(allResponse) {
  86. var result = [];
  87. _.each(allResponse, function(response, index) {
  88. if (response.status === 'error') {
  89. self.lastErrors.query = response.error;
  90. throw response.error;
  91. }
  92. delete self.lastErrors.query;
  93. _.each(response.data.data.result, function(metricData) {
  94. result.push(self.transformMetricData(metricData, activeTargets[index], start, end));
  95. });
  96. });
  97. return { data: result };
  98. });
  99. };
  100. this.adjustStep = function(step, autoStep, range) {
  101. // Prometheus drop query if range/step > 11000
  102. // calibrate step if it is too big
  103. if (step !== 0 && range / step > 11000) {
  104. return Math.ceil(range / 11000);
  105. }
  106. return Math.max(step, autoStep);
  107. };
  108. this.performTimeSeriesQuery = function(query, start, end) {
  109. if (start > end) {
  110. throw { message: 'Invalid time range' };
  111. }
  112. var url = '/api/v1/query_range?query=' + encodeURIComponent(query.expr) + '&start=' + start + '&end=' + end + '&step=' + query.step;
  113. return this._request('GET', url, query.requestId);
  114. };
  115. this.performSuggestQuery = function(query) {
  116. var url = '/api/v1/label/__name__/values';
  117. return this._request('GET', url).then(function(result) {
  118. return _.filter(result.data.data, function (metricName) {
  119. return metricName.indexOf(query) !== 1;
  120. });
  121. });
  122. };
  123. this.metricFindQuery = function(query) {
  124. if (!query) { return $q.when([]); }
  125. var interpolated;
  126. try {
  127. interpolated = templateSrv.replace(query, {}, this.interpolateQueryExpr);
  128. } catch (err) {
  129. return $q.reject(err);
  130. }
  131. var metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, timeSrv);
  132. return metricFindQuery.process();
  133. };
  134. this.annotationQuery = function(options) {
  135. var annotation = options.annotation;
  136. var expr = annotation.expr || '';
  137. var tagKeys = annotation.tagKeys || '';
  138. var titleFormat = annotation.titleFormat || '';
  139. var textFormat = annotation.textFormat || '';
  140. if (!expr) { return $q.when([]); }
  141. var interpolated;
  142. try {
  143. interpolated = templateSrv.replace(expr, {}, this.interpolateQueryExpr);
  144. } catch (err) {
  145. return $q.reject(err);
  146. }
  147. var step = '60s';
  148. if (annotation.step) {
  149. step = templateSrv.replace(annotation.step);
  150. }
  151. var start = this.getPrometheusTime(options.range.from, false);
  152. var end = this.getPrometheusTime(options.range.to, true);
  153. var query = {
  154. expr: interpolated,
  155. step: this.adjustStep(kbn.interval_to_seconds(step), 0, Math.ceil(end - start)) + 's'
  156. };
  157. var self = this;
  158. return this.performTimeSeriesQuery(query, start, end).then(function(results) {
  159. var eventList = [];
  160. tagKeys = tagKeys.split(',');
  161. _.each(results.data.data.result, function(series) {
  162. var tags = _.chain(series.metric)
  163. .filter(function(v, k) {
  164. return _.includes(tagKeys, k);
  165. }).value();
  166. _.each(series.values, function(value) {
  167. if (value[1] === '1') {
  168. var event = {
  169. annotation: annotation,
  170. time: Math.floor(value[0]) * 1000,
  171. title: self.renderTemplate(titleFormat, series.metric),
  172. tags: tags,
  173. text: self.renderTemplate(textFormat, series.metric)
  174. };
  175. eventList.push(event);
  176. }
  177. });
  178. });
  179. return eventList;
  180. });
  181. };
  182. this.testDatasource = function() {
  183. return this.metricFindQuery('metrics(.*)').then(function() {
  184. return { status: 'success', message: 'Data source is working', title: 'Success' };
  185. });
  186. };
  187. this.calculateInterval = function(interval, intervalFactor) {
  188. return Math.ceil(this.intervalSeconds(interval) * intervalFactor);
  189. };
  190. this.intervalSeconds = function(interval) {
  191. var m = interval.match(durationSplitRegexp);
  192. var dur = moment.duration(parseInt(m[1]), m[2]);
  193. var sec = dur.asSeconds();
  194. if (sec < 1) {
  195. sec = 1;
  196. }
  197. return sec;
  198. };
  199. this.transformMetricData = function(md, options, start, end) {
  200. var dps = [],
  201. metricLabel = null;
  202. metricLabel = this.createMetricLabel(md.metric, options);
  203. var stepMs = parseInt(options.step) * 1000;
  204. var baseTimestamp = start * 1000;
  205. _.each(md.values, function(value) {
  206. var dp_value = parseFloat(value[1]);
  207. if (_.isNaN(dp_value)) {
  208. dp_value = null;
  209. }
  210. var timestamp = value[0] * 1000;
  211. for (var t = baseTimestamp; t < timestamp; t += stepMs) {
  212. dps.push([null, t]);
  213. }
  214. baseTimestamp = timestamp + stepMs;
  215. dps.push([dp_value, timestamp]);
  216. });
  217. var endTimestamp = end * 1000;
  218. for (var t = baseTimestamp; t <= endTimestamp; t += stepMs) {
  219. dps.push([null, t]);
  220. }
  221. return { target: metricLabel, datapoints: dps };
  222. };
  223. this.createMetricLabel = function(labelData, options) {
  224. if (_.isUndefined(options) || _.isEmpty(options.legendFormat)) {
  225. return this.getOriginalMetricName(labelData);
  226. }
  227. return this.renderTemplate(templateSrv.replace(options.legendFormat), labelData) || '{}';
  228. };
  229. this.renderTemplate = function(aliasPattern, aliasData) {
  230. var aliasRegex = /\{\{\s*(.+?)\s*\}\}/g;
  231. return aliasPattern.replace(aliasRegex, function(match, g1) {
  232. if (aliasData[g1]) {
  233. return aliasData[g1];
  234. }
  235. return g1;
  236. });
  237. };
  238. this.getOriginalMetricName = function(labelData) {
  239. var metricName = labelData.__name__ || '';
  240. delete labelData.__name__;
  241. var labelPart = _.map(_.toPairs(labelData), function(label) {
  242. return label[0] + '="' + label[1] + '"';
  243. }).join(',');
  244. return metricName + '{' + labelPart + '}';
  245. };
  246. this.getPrometheusTime = function(date, roundUp) {
  247. if (_.isString(date)) {
  248. date = dateMath.parse(date, roundUp);
  249. }
  250. return Math.ceil(date.valueOf() / 1000);
  251. };
  252. }