templateValuesSrv.js 10 KB

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