datasource.ts 8.3 KB

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