datasource.ts 8.3 KB

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