datasource.ts 7.7 KB

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