datasource.ts 8.0 KB

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