datasource.ts 8.2 KB

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