datasource.ts 8.3 KB

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