datasource.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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, $http, 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);
  37. var alias = target.alias ? templateSrv.replace(target.alias) : '';
  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.metricFindQuery = function (query) {
  82. var interpolated;
  83. try {
  84. interpolated = templateSrv.replace(query);
  85. }
  86. catch (err) {
  87. return $q.reject(err);
  88. }
  89. return this._seriesQuery(interpolated)
  90. .then(function (results) {
  91. if (!results || results.length === 0) { return []; }
  92. return _.map(results[0].points, function (metric) {
  93. return {
  94. text: metric[1],
  95. expandable: false
  96. };
  97. });
  98. });
  99. };
  100. function retry(deferred, callback, delay) {
  101. return callback().then(undefined, function(reason) {
  102. if (reason.status !== 0 || reason.status >= 300) {
  103. reason.message = 'InfluxDB Error: <br/>' + reason.data;
  104. deferred.reject(reason);
  105. }
  106. else {
  107. setTimeout(function() {
  108. return retry(deferred, callback, Math.min(delay * 2, 30000));
  109. }, delay);
  110. }
  111. });
  112. }
  113. InfluxDatasource.prototype._seriesQuery = function(query) {
  114. return this._influxRequest('GET', '/series', {
  115. q: query,
  116. });
  117. };
  118. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  119. var _this = this;
  120. var deferred = $q.defer();
  121. retry(deferred, function() {
  122. var currentUrl = _this.urls.shift();
  123. _this.urls.push(currentUrl);
  124. var params = {
  125. u: _this.username,
  126. p: _this.password,
  127. };
  128. if (method === 'GET') {
  129. _.extend(params, data);
  130. data = null;
  131. }
  132. var options = {
  133. method: method,
  134. url: currentUrl + url,
  135. params: params,
  136. data: data,
  137. inspect: { type: 'influxdb' },
  138. };
  139. options.headers = options.headers || {};
  140. if (_this.basicAuth) {
  141. options.headers.Authorization = 'Basic ' + _this.basicAuth;
  142. }
  143. return $http(options).success(function (data) {
  144. deferred.resolve(data);
  145. });
  146. }, 10);
  147. return deferred.promise;
  148. };
  149. InfluxDatasource.prototype.saveDashboard = function(dashboard) {
  150. var tags = dashboard.tags.join(',');
  151. var title = dashboard.title;
  152. var temp = dashboard.temp;
  153. var id = kbn.slugifyForUrl(title);
  154. if (temp) { delete dashboard.temp; }
  155. var data = [{
  156. name: 'grafana.dashboard_' + btoa(id),
  157. columns: ['time', 'sequence_number', 'title', 'tags', 'dashboard', 'id'],
  158. points: [[1000000000000, 1, title, tags, angular.toJson(dashboard), id]]
  159. }];
  160. if (temp) {
  161. return this._saveDashboardTemp(data, title, id);
  162. }
  163. else {
  164. var self = this;
  165. return this._influxRequest('POST', '/series', data).then(function() {
  166. self._removeUnslugifiedDashboard(id, title, false);
  167. return { title: title, url: '/dashboard/db/' + id };
  168. }, function(err) {
  169. throw 'Failed to save dashboard to InfluxDB: ' + err.data;
  170. });
  171. }
  172. };
  173. InfluxDatasource.prototype._removeUnslugifiedDashboard = function(id, title, isTemp) {
  174. if (id === title) { return; }
  175. var self = this;
  176. self._getDashboardInternal(title, isTemp).then(function(dashboard) {
  177. if (dashboard !== null) {
  178. self.deleteDashboard(title);
  179. }
  180. });
  181. };
  182. InfluxDatasource.prototype._saveDashboardTemp = function(data, title, id) {
  183. data[0].name = 'grafana.temp_dashboard_' + btoa(id);
  184. data[0].columns.push('expires');
  185. data[0].points[0].push(this._getTempDashboardExpiresDate());
  186. return this._influxRequest('POST', '/series', data).then(function() {
  187. var baseUrl = window.location.href.replace(window.location.hash,'');
  188. var url = baseUrl + "#dashboard/temp/" + id;
  189. return { title: title, url: url };
  190. }, function(err) {
  191. throw 'Failed to save shared dashboard to InfluxDB: ' + err.data;
  192. });
  193. };
  194. InfluxDatasource.prototype._getTempDashboardExpiresDate = function() {
  195. var ttlLength = this.saveTempTTL.substring(0, this.saveTempTTL.length - 1);
  196. var ttlTerm = this.saveTempTTL.substring(this.saveTempTTL.length - 1, this.saveTempTTL.length).toLowerCase();
  197. var expires = Date.now();
  198. switch(ttlTerm) {
  199. case "m":
  200. expires += ttlLength * 60000;
  201. break;
  202. case "d":
  203. expires += ttlLength * 86400000;
  204. break;
  205. case "w":
  206. expires += ttlLength * 604800000;
  207. break;
  208. default:
  209. throw "Unknown ttl duration format";
  210. }
  211. return expires;
  212. };
  213. InfluxDatasource.prototype._getDashboardInternal = function(id, isTemp) {
  214. var queryString = 'select dashboard from "grafana.dashboard_' + btoa(id) + '"';
  215. if (isTemp) {
  216. queryString = 'select dashboard from "grafana.temp_dashboard_' + btoa(id) + '"';
  217. }
  218. return this._seriesQuery(queryString).then(function(results) {
  219. if (!results || !results.length) {
  220. return null;
  221. }
  222. var dashCol = _.indexOf(results[0].columns, 'dashboard');
  223. var dashJson = results[0].points[0][dashCol];
  224. return angular.fromJson(dashJson);
  225. }, function() {
  226. return null;
  227. });
  228. };
  229. InfluxDatasource.prototype.getDashboard = function(id, isTemp) {
  230. var self = this;
  231. return this._getDashboardInternal(id, isTemp).then(function(dashboard) {
  232. if (dashboard !== null) {
  233. return dashboard;
  234. }
  235. // backward compatible load for unslugified ids
  236. var slug = kbn.slugifyForUrl(id);
  237. if (slug !== id) {
  238. return self.getDashboard(slug, isTemp);
  239. }
  240. throw "Dashboard not found";
  241. }, function(err) {
  242. throw "Could not load dashboard, " + err.data;
  243. });
  244. };
  245. InfluxDatasource.prototype.deleteDashboard = function(id) {
  246. return this._seriesQuery('drop series "grafana.dashboard_' + btoa(id) + '"').then(function(results) {
  247. if (!results) {
  248. throw "Could not delete dashboard";
  249. }
  250. return id;
  251. }, function(err) {
  252. throw "Could not delete dashboard, " + err.data;
  253. });
  254. };
  255. InfluxDatasource.prototype.searchDashboards = function(queryString) {
  256. var influxQuery = 'select * from /grafana.dashboard_.*/ where ';
  257. var tagsOnly = queryString.indexOf('tags!:') === 0;
  258. if (tagsOnly) {
  259. var tagsQuery = queryString.substring(6, queryString.length);
  260. influxQuery = influxQuery + 'tags =~ /.*' + tagsQuery + '.*/i';
  261. }
  262. else {
  263. var titleOnly = queryString.indexOf('title:') === 0;
  264. if (titleOnly) {
  265. var titleQuery = queryString.substring(6, queryString.length);
  266. influxQuery = influxQuery + ' title =~ /.*' + titleQuery + '.*/i';
  267. }
  268. else {
  269. influxQuery = influxQuery + '(tags =~ /.*' + queryString + '.*/i or title =~ /.*' + queryString + '.*/i)';
  270. }
  271. }
  272. return this._seriesQuery(influxQuery).then(function(results) {
  273. var hits = { dashboards: [], tags: [], tagsOnly: false };
  274. if (!results || !results.length) {
  275. return hits;
  276. }
  277. for (var i = 0; i < results.length; i++) {
  278. var dashCol = _.indexOf(results[i].columns, 'title');
  279. var tagsCol = _.indexOf(results[i].columns, 'tags');
  280. var idCol = _.indexOf(results[i].columns, 'id');
  281. var hit = {
  282. id: results[i].points[0][dashCol],
  283. title: results[i].points[0][dashCol],
  284. tags: results[i].points[0][tagsCol].split(",")
  285. };
  286. if (idCol !== -1) {
  287. hit.id = results[i].points[0][idCol];
  288. }
  289. hit.tags = hit.tags[0] ? hit.tags : [];
  290. hits.dashboards.push(hit);
  291. }
  292. return hits;
  293. });
  294. };
  295. function handleInfluxQueryResponse(alias, groupByField, seriesList) {
  296. var influxSeries = new InfluxSeries({
  297. seriesList: seriesList,
  298. alias: alias,
  299. groupByField: groupByField
  300. });
  301. return influxSeries.getTimeSeries();
  302. }
  303. function getTimeFilter(options) {
  304. var from = getInfluxTime(options.range.from);
  305. var until = getInfluxTime(options.range.to);
  306. var fromIsAbsolute = from[from.length-1] === 's';
  307. if (until === 'now()' && !fromIsAbsolute) {
  308. return 'time > ' + from;
  309. }
  310. return 'time > ' + from + ' and time < ' + until;
  311. }
  312. function getInfluxTime(date) {
  313. if (_.isString(date)) {
  314. return date.replace('now', 'now()');
  315. }
  316. return to_utc_epoch_seconds(date);
  317. }
  318. function to_utc_epoch_seconds(date) {
  319. return (date.getTime() / 1000).toFixed(0) + 's';
  320. }
  321. return InfluxDatasource;
  322. });
  323. });