datasource.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'kbn',
  5. './influxSeries',
  6. './queryBuilder',
  7. './queryCtrl',
  8. './funcEditor',
  9. ],
  10. function (angular, _, kbn, InfluxSeries, InfluxQueryBuilder) {
  11. 'use strict';
  12. var module = angular.module('grafana.services');
  13. module.factory('InfluxDatasource_08', function($q, backendSrv, templateSrv) {
  14. function InfluxDatasource(datasource) {
  15. this.urls = _.map(datasource.url.split(','), function(url) {
  16. return url.trim();
  17. });
  18. this.username = datasource.username;
  19. this.password = datasource.password;
  20. this.name = datasource.name;
  21. this.basicAuth = datasource.basicAuth;
  22. }
  23. InfluxDatasource.prototype.query = function(options) {
  24. var timeFilter = getTimeFilter(options);
  25. var promises = _.map(options.targets, function(target) {
  26. if (target.hide || !((target.series && target.column) || target.query)) {
  27. return [];
  28. }
  29. // build query
  30. var queryBuilder = new InfluxQueryBuilder(target);
  31. var query = queryBuilder.build();
  32. // replace grafana variables
  33. query = query.replace('$timeFilter', timeFilter);
  34. query = query.replace(/\$interval/g, (target.interval || options.interval));
  35. // replace templated variables
  36. query = templateSrv.replace(query, options.scopedVars);
  37. var alias = target.alias ? templateSrv.replace(target.alias, options.scopedVars) : '';
  38. var handleResponse = _.partial(handleInfluxQueryResponse, alias, queryBuilder.groupByField);
  39. return this._seriesQuery(query).then(handleResponse);
  40. }, this);
  41. return $q.all(promises).then(function(results) {
  42. return { data: _.flatten(results) };
  43. });
  44. };
  45. InfluxDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  46. var timeFilter = getTimeFilter({ range: rangeUnparsed });
  47. var query = annotation.query.replace('$timeFilter', timeFilter);
  48. query = templateSrv.replace(query);
  49. return this._seriesQuery(query).then(function(results) {
  50. return new InfluxSeries({ seriesList: results, annotation: annotation }).getAnnotations();
  51. });
  52. };
  53. InfluxDatasource.prototype.listColumns = function(seriesName) {
  54. seriesName = templateSrv.replace(seriesName);
  55. if(!seriesName.match('^/.*/') && !seriesName.match(/^merge\(.*\)/)) {
  56. seriesName = '"' + seriesName+ '"';
  57. }
  58. return this._seriesQuery('select * from ' + seriesName + ' limit 1').then(function(data) {
  59. if (!data) {
  60. return [];
  61. }
  62. return data[0].columns.map(function(item) {
  63. return /^\w+$/.test(item) ? item : ('"' + item + '"');
  64. });
  65. });
  66. };
  67. InfluxDatasource.prototype.listSeries = function(query) {
  68. // wrap in regex
  69. if (query && query.length > 0 && query[0] !== '/') {
  70. query = '/' + query + '/';
  71. }
  72. return this._seriesQuery('list series ' + query).then(function(data) {
  73. if (!data || data.length === 0) {
  74. return [];
  75. }
  76. return _.map(data[0].points, function(point) {
  77. return point[1];
  78. });
  79. });
  80. };
  81. InfluxDatasource.prototype.testDatasource = function() {
  82. return this.metricFindQuery('list series').then(function () {
  83. return { status: "success", message: "Data source is working", title: "Success" };
  84. });
  85. };
  86. InfluxDatasource.prototype.metricFindQuery = function (query) {
  87. var interpolated;
  88. try {
  89. interpolated = templateSrv.replace(query);
  90. }
  91. catch (err) {
  92. return $q.reject(err);
  93. }
  94. return this._seriesQuery(interpolated)
  95. .then(function (results) {
  96. if (!results || results.length === 0) { return []; }
  97. return _.map(results[0].points, function (metric) {
  98. return {
  99. text: metric[1],
  100. expandable: false
  101. };
  102. });
  103. });
  104. };
  105. function retry(deferred, callback, delay) {
  106. return callback().then(undefined, function(reason) {
  107. if (reason.status !== 0 || reason.status >= 300) {
  108. reason.message = 'InfluxDB Error: <br/>' + reason.data;
  109. deferred.reject(reason);
  110. }
  111. else {
  112. setTimeout(function() {
  113. return retry(deferred, callback, Math.min(delay * 2, 30000));
  114. }, delay);
  115. }
  116. });
  117. }
  118. InfluxDatasource.prototype._seriesQuery = function(query) {
  119. return this._influxRequest('GET', '/series', {
  120. q: query,
  121. });
  122. };
  123. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  124. var _this = this;
  125. var deferred = $q.defer();
  126. retry(deferred, function() {
  127. var currentUrl = _this.urls.shift();
  128. _this.urls.push(currentUrl);
  129. var params = {
  130. u: _this.username,
  131. p: _this.password,
  132. };
  133. if (method === 'GET') {
  134. _.extend(params, data);
  135. data = null;
  136. }
  137. var options = {
  138. method: method,
  139. url: currentUrl + url,
  140. params: params,
  141. data: data,
  142. inspect: { type: 'influxdb' },
  143. };
  144. options.headers = options.headers || {};
  145. if (_this.basicAuth) {
  146. options.headers.Authorization = 'Basic ' + _this.basicAuth;
  147. }
  148. return backendSrv.datasourceRequest(options).then(function(response) {
  149. deferred.resolve(response.data);
  150. });
  151. }, 10);
  152. return deferred.promise;
  153. };
  154. InfluxDatasource.prototype._getDashboardInternal = function(id, isTemp) {
  155. var queryString = 'select dashboard from "grafana.dashboard_' + btoa(id) + '"';
  156. if (isTemp) {
  157. queryString = 'select dashboard from "grafana.temp_dashboard_' + btoa(id) + '"';
  158. }
  159. return this._seriesQuery(queryString).then(function(results) {
  160. if (!results || !results.length) {
  161. return null;
  162. }
  163. var dashCol = _.indexOf(results[0].columns, 'dashboard');
  164. var dashJson = results[0].points[0][dashCol];
  165. return angular.fromJson(dashJson);
  166. }, function() {
  167. return null;
  168. });
  169. };
  170. InfluxDatasource.prototype.getDashboard = function(id, isTemp) {
  171. var self = this;
  172. return this._getDashboardInternal(id, isTemp).then(function(dashboard) {
  173. if (dashboard !== null) {
  174. return dashboard;
  175. }
  176. // backward compatible load for unslugified ids
  177. var slug = kbn.slugifyForUrl(id);
  178. if (slug !== id) {
  179. return self.getDashboard(slug, isTemp);
  180. }
  181. throw "Dashboard not found";
  182. }, function(err) {
  183. throw "Could not load dashboard, " + err.data;
  184. });
  185. };
  186. InfluxDatasource.prototype.deleteDashboard = function(id) {
  187. return this._seriesQuery('drop series "grafana.dashboard_' + btoa(id) + '"').then(function(results) {
  188. if (!results) {
  189. throw "Could not delete dashboard";
  190. }
  191. return id;
  192. }, function(err) {
  193. throw "Could not delete dashboard, " + err.data;
  194. });
  195. };
  196. InfluxDatasource.prototype.searchDashboards = function(queryString) {
  197. var influxQuery = 'select * from /grafana.dashboard_.*/ where ';
  198. var tagsOnly = queryString.indexOf('tags!:') === 0;
  199. if (tagsOnly) {
  200. var tagsQuery = queryString.substring(6, queryString.length);
  201. influxQuery = influxQuery + 'tags =~ /.*' + tagsQuery + '.*/i';
  202. }
  203. else {
  204. var titleOnly = queryString.indexOf('title:') === 0;
  205. if (titleOnly) {
  206. var titleQuery = queryString.substring(6, queryString.length);
  207. influxQuery = influxQuery + ' title =~ /.*' + titleQuery + '.*/i';
  208. }
  209. else {
  210. influxQuery = influxQuery + '(tags =~ /.*' + queryString + '.*/i or title =~ /.*' + queryString + '.*/i)';
  211. }
  212. }
  213. return this._seriesQuery(influxQuery).then(function(results) {
  214. var hits = { dashboards: [], tags: [], tagsOnly: false };
  215. if (!results || !results.length) {
  216. return hits;
  217. }
  218. for (var i = 0; i < results.length; i++) {
  219. var dashCol = _.indexOf(results[i].columns, 'title');
  220. var tagsCol = _.indexOf(results[i].columns, 'tags');
  221. var idCol = _.indexOf(results[i].columns, 'id');
  222. var hit = {
  223. id: results[i].points[0][dashCol],
  224. title: results[i].points[0][dashCol],
  225. tags: results[i].points[0][tagsCol].split(",")
  226. };
  227. if (idCol !== -1) {
  228. hit.id = results[i].points[0][idCol];
  229. }
  230. hit.tags = hit.tags[0] ? hit.tags : [];
  231. hits.dashboards.push(hit);
  232. }
  233. return hits;
  234. });
  235. };
  236. function handleInfluxQueryResponse(alias, groupByField, seriesList) {
  237. var influxSeries = new InfluxSeries({
  238. seriesList: seriesList,
  239. alias: alias,
  240. groupByField: groupByField
  241. });
  242. return influxSeries.getTimeSeries();
  243. }
  244. function getTimeFilter(options) {
  245. var from = getInfluxTime(options.range.from);
  246. var until = getInfluxTime(options.range.to);
  247. var fromIsAbsolute = from[from.length-1] === 's';
  248. if (until === 'now()' && !fromIsAbsolute) {
  249. return 'time > ' + from;
  250. }
  251. return 'time > ' + from + ' and time < ' + until;
  252. }
  253. function getInfluxTime(date) {
  254. if (_.isString(date)) {
  255. return date.replace('now', 'now()');
  256. }
  257. return to_utc_epoch_seconds(date);
  258. }
  259. function to_utc_epoch_seconds(date) {
  260. return (date.getTime() / 1000).toFixed(0) + 's';
  261. }
  262. return InfluxDatasource;
  263. });
  264. });