templateValuesSrv.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'jquery',
  5. 'app/core/utils/kbn',
  6. ],
  7. function (angular, _, $, kbn) {
  8. 'use strict';
  9. var module = angular.module('grafana.services');
  10. module.service('templateValuesSrv', function($q, $rootScope, datasourceSrv, $location, templateSrv, timeSrv) {
  11. var self = this;
  12. function getNoneOption() { return { text: 'None', value: '', isNone: true }; }
  13. // update time variant variables
  14. $rootScope.onAppEvent('refresh', function() {
  15. // look for interval variables
  16. var intervalVariable = _.findWhere(self.variables, { type: 'interval' });
  17. if (intervalVariable) {
  18. self.updateAutoInterval(intervalVariable);
  19. }
  20. // update variables with refresh === 2
  21. var promises = self.variables
  22. .filter(function(variable) {
  23. return variable.refresh === 2;
  24. }).map(function(variable) {
  25. var previousOptions = variable.options.slice();
  26. return self.updateOptions(variable).then(function () {
  27. return self.variableUpdated(variable).then(function () {
  28. // check if current options changed due to refresh
  29. if (angular.toJson(previousOptions) !== angular.toJson(variable.options)) {
  30. $rootScope.appEvent('template-variable-value-updated');
  31. }
  32. });
  33. });
  34. });
  35. return $q.all(promises);
  36. }, $rootScope);
  37. this.init = function(dashboard) {
  38. this.dashboard = dashboard;
  39. this.variables = dashboard.templating.list;
  40. templateSrv.init(this.variables);
  41. var queryParams = $location.search();
  42. var promises = [];
  43. // use promises to delay processing variables that
  44. // depend on other variables.
  45. this.variableLock = {};
  46. _.forEach(this.variables, function(variable) {
  47. self.variableLock[variable.name] = $q.defer();
  48. });
  49. for (var i = 0; i < this.variables.length; i++) {
  50. var variable = this.variables[i];
  51. promises.push(this.processVariable(variable, queryParams));
  52. }
  53. return $q.all(promises);
  54. };
  55. this.processVariable = function(variable, queryParams) {
  56. var dependencies = [];
  57. var lock = self.variableLock[variable.name];
  58. // determine our dependencies.
  59. if (variable.type === "query") {
  60. _.forEach(this.variables, function(v) {
  61. // both query and datasource can contain variable
  62. if (templateSrv.containsVariable(variable.query, v.name) ||
  63. templateSrv.containsVariable(variable.datasource, v.name)) {
  64. dependencies.push(self.variableLock[v.name].promise);
  65. }
  66. });
  67. }
  68. return $q.all(dependencies).then(function() {
  69. var urlValue = queryParams['var-' + variable.name];
  70. if (urlValue !== void 0) {
  71. return self.setVariableFromUrl(variable, urlValue).then(lock.resolve);
  72. }
  73. else if (variable.refresh === 1 || variable.refresh === 2) {
  74. return self.updateOptions(variable).then(function() {
  75. if (_.isEmpty(variable.current) && variable.options.length) {
  76. self.setVariableValue(variable, variable.options[0]);
  77. }
  78. lock.resolve();
  79. });
  80. }
  81. else if (variable.type === 'interval') {
  82. self.updateAutoInterval(variable);
  83. lock.resolve();
  84. } else {
  85. lock.resolve();
  86. }
  87. });
  88. };
  89. this.setVariableFromUrl = function(variable, urlValue) {
  90. var promise = $q.when(true);
  91. if (variable.refresh) {
  92. promise = this.updateOptions(variable);
  93. }
  94. return promise.then(function() {
  95. var option = _.find(variable.options, function(op) {
  96. return op.text === urlValue || op.value === urlValue;
  97. });
  98. option = option || { text: urlValue, value: urlValue };
  99. self.updateAutoInterval(variable);
  100. return self.setVariableValue(variable, option, true);
  101. });
  102. };
  103. this.updateAutoInterval = function(variable) {
  104. if (!variable.auto) { return; }
  105. // add auto option if missing
  106. if (variable.options.length && variable.options[0].text !== 'auto') {
  107. variable.options.unshift({ text: 'auto', value: '$__auto_interval' });
  108. }
  109. var interval = kbn.calculateInterval(timeSrv.timeRange(), variable.auto_count, (variable.auto_min ? ">"+variable.auto_min : null));
  110. templateSrv.setGrafanaVariable('$__auto_interval', interval);
  111. };
  112. this.setVariableValue = function(variable, option, initPhase) {
  113. variable.current = angular.copy(option);
  114. if (_.isArray(variable.current.text)) {
  115. variable.current.text = variable.current.text.join(' + ');
  116. }
  117. self.selectOptionsForCurrentValue(variable);
  118. templateSrv.updateTemplateData();
  119. // on first load, variable loading is ordered to ensure
  120. // that parents are updated before children.
  121. if (initPhase) {
  122. return $q.when();
  123. }
  124. return self.updateOptionsInChildVariables(variable);
  125. };
  126. this.variableUpdated = function(variable) {
  127. templateSrv.updateTemplateData();
  128. return self.updateOptionsInChildVariables(variable);
  129. };
  130. this.updateOptionsInChildVariables = function(updatedVariable) {
  131. var promises = _.map(self.variables, function(otherVariable) {
  132. if (otherVariable === updatedVariable) {
  133. return;
  134. }
  135. if (templateSrv.containsVariable(otherVariable.query, updatedVariable.name) ||
  136. templateSrv.containsVariable(otherVariable.datasource, updatedVariable.name)) {
  137. return self.updateOptions(otherVariable);
  138. }
  139. });
  140. return $q.all(promises);
  141. };
  142. this._updateNonQueryVariable = function(variable) {
  143. if (variable.type === 'datasource') {
  144. self.updateDataSourceVariable(variable);
  145. return;
  146. }
  147. if (variable.type === 'constant') {
  148. variable.options = [{text: variable.query, value: variable.query}];
  149. return;
  150. }
  151. // extract options in comma separated string
  152. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  153. return { text: text.trim(), value: text.trim() };
  154. });
  155. if (variable.type === 'interval') {
  156. self.updateAutoInterval(variable);
  157. return;
  158. }
  159. if (variable.type === 'custom' && variable.includeAll) {
  160. self.addAllOption(variable);
  161. }
  162. };
  163. this.updateDataSourceVariable = function(variable) {
  164. var options = [];
  165. var sources = datasourceSrv.getMetricSources({skipVariables: true});
  166. var regex;
  167. if (variable.regex) {
  168. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  169. }
  170. for (var i = 0; i < sources.length; i++) {
  171. var source = sources[i];
  172. // must match on type
  173. if (source.meta.id !== variable.query) {
  174. continue;
  175. }
  176. if (regex && !regex.exec(source.name)) {
  177. continue;
  178. }
  179. options.push({text: source.name, value: source.name});
  180. }
  181. if (options.length === 0) {
  182. options.push({text: 'No data sources found', value: ''});
  183. }
  184. variable.options = options;
  185. };
  186. this.updateOptions = function(variable) {
  187. if (variable.type !== 'query') {
  188. self._updateNonQueryVariable(variable);
  189. return self.validateVariableSelectionState(variable);
  190. }
  191. return datasourceSrv.get(variable.datasource)
  192. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  193. .then(_.partial(this.updateTags, variable))
  194. .then(_.partial(this.validateVariableSelectionState, variable));
  195. };
  196. this.selectOptionsForCurrentValue = function(variable) {
  197. var i, y, value, option;
  198. var selected = [];
  199. for (i = 0; i < variable.options.length; i++) {
  200. option = variable.options[i];
  201. option.selected = false;
  202. if (_.isArray(variable.current.value)) {
  203. for (y = 0; y < variable.current.value.length; y++) {
  204. value = variable.current.value[y];
  205. if (option.value === value) {
  206. option.selected = true;
  207. selected.push(option);
  208. }
  209. }
  210. } else if (option.value === variable.current.value) {
  211. option.selected = true;
  212. selected.push(option);
  213. }
  214. }
  215. return selected;
  216. };
  217. this.validateVariableSelectionState = function(variable) {
  218. if (!variable.current) {
  219. if (!variable.options.length) { return; }
  220. return self.setVariableValue(variable, variable.options[0], false);
  221. }
  222. if (_.isArray(variable.current.value)) {
  223. var selected = self.selectOptionsForCurrentValue(variable);
  224. // if none pick first
  225. if (selected.length === 0) {
  226. selected = variable.options[0];
  227. } else {
  228. selected = {
  229. value: _.map(selected, function(val) {return val.value;}),
  230. text: _.map(selected, function(val) {return val.text;}).join(' + '),
  231. };
  232. }
  233. return self.setVariableValue(variable, selected, false);
  234. } else {
  235. var currentOption = _.findWhere(variable.options, {text: variable.current.text});
  236. if (currentOption) {
  237. return self.setVariableValue(variable, currentOption, false);
  238. } else {
  239. if (!variable.options.length) { return $q.when(null); }
  240. return self.setVariableValue(variable, variable.options[0]);
  241. }
  242. }
  243. };
  244. this.updateTags = function(variable, datasource) {
  245. if (variable.useTags) {
  246. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  247. variable.tags = [];
  248. for (var i = 0; i < results.length; i++) {
  249. variable.tags.push(results[i].text);
  250. }
  251. return datasource;
  252. });
  253. } else {
  254. delete variable.tags;
  255. }
  256. return datasource;
  257. };
  258. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  259. return datasource.metricFindQuery(variable.query).then(function (results) {
  260. variable.options = self.metricNamesToVariableValues(variable, results);
  261. if (variable.includeAll) {
  262. self.addAllOption(variable);
  263. }
  264. if (!variable.options.length) {
  265. variable.options.push(getNoneOption());
  266. }
  267. return datasource;
  268. });
  269. };
  270. this.getValuesForTag = function(variable, tagKey) {
  271. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  272. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  273. return datasource.metricFindQuery(query).then(function (results) {
  274. return _.map(results, function(value) {
  275. return value.text;
  276. });
  277. });
  278. });
  279. };
  280. this.metricNamesToVariableValues = function(variable, metricNames) {
  281. var regex, options, i, matches;
  282. options = {}; // use object hash to remove duplicates
  283. if (variable.regex) {
  284. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  285. }
  286. for (i = 0; i < metricNames.length; i++) {
  287. var item = metricNames[i];
  288. var value = item.value || item.text;
  289. var text = item.text || item.value;
  290. if (_.isNumber(value)) {
  291. value = value.toString();
  292. }
  293. if (_.isNumber(text)) {
  294. text = text.toString();
  295. }
  296. if (regex) {
  297. matches = regex.exec(value);
  298. if (!matches) { continue; }
  299. if (matches.length > 1) {
  300. value = matches[1];
  301. text = value;
  302. }
  303. }
  304. options[value] = {text: text, value: value};
  305. }
  306. return _.sortBy(options, 'text');
  307. };
  308. this.addAllOption = function(variable) {
  309. variable.options.unshift({text: 'All', value: "$__all"});
  310. };
  311. });
  312. });