templateValuesSrv.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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, dynamicDashboardSrv) {
  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. var previousVariable = angular.copy(variable);
  25. return self.updateOptions(variable).then(function () {
  26. return self.variableUpdated(variable).then(function () {
  27. var updatedVariable = angular.copy(variable);
  28. delete(updatedVariable.$$hashKey);
  29. if (JSON.stringify(previousVariable) !== JSON.stringify(updatedVariable)) {
  30. dynamicDashboardSrv.update(self.dashboard);
  31. $rootScope.$emit('template-variable-value-updated');
  32. }
  33. });
  34. });
  35. });
  36. return $q.all(promises);
  37. }, $rootScope);
  38. this.init = function(dashboard) {
  39. this.dashboard = dashboard;
  40. this.variables = dashboard.templating.list;
  41. templateSrv.init(this.variables);
  42. var queryParams = $location.search();
  43. var promises = [];
  44. // use promises to delay processing variables that
  45. // depend on other variables.
  46. this.variableLock = {};
  47. _.forEach(this.variables, function(variable) {
  48. self.variableLock[variable.name] = $q.defer();
  49. });
  50. for (var i = 0; i < this.variables.length; i++) {
  51. var variable = this.variables[i];
  52. promises.push(this.processVariable(variable, queryParams));
  53. }
  54. return $q.all(promises);
  55. };
  56. this.processVariable = function(variable, queryParams) {
  57. var dependencies = [];
  58. var lock = self.variableLock[variable.name];
  59. // determine our dependencies.
  60. if (variable.type === "query") {
  61. _.forEach(this.variables, function(v) {
  62. // both query and datasource can contain variable
  63. if (templateSrv.containsVariable(variable.query, v.name) ||
  64. templateSrv.containsVariable(variable.datasource, v.name)) {
  65. dependencies.push(self.variableLock[v.name].promise);
  66. }
  67. });
  68. }
  69. return $q.all(dependencies).then(function() {
  70. var urlValue = queryParams['var-' + variable.name];
  71. if (urlValue !== void 0) {
  72. return self.setVariableFromUrl(variable, urlValue).then(lock.resolve);
  73. }
  74. else if (variable.refresh === 1 || variable.refresh === 2) {
  75. return self.updateOptions(variable).then(function() {
  76. if (_.isEmpty(variable.current) && variable.options.length) {
  77. console.log("setting current for %s", variable.name);
  78. self.setVariableValue(variable, variable.options[0]);
  79. }
  80. lock.resolve();
  81. });
  82. }
  83. else if (variable.type === 'interval') {
  84. self.updateAutoInterval(variable);
  85. lock.resolve();
  86. } else {
  87. lock.resolve();
  88. }
  89. });
  90. };
  91. this.setVariableFromUrl = function(variable, urlValue) {
  92. var promise = $q.when(true);
  93. if (variable.refresh) {
  94. promise = this.updateOptions(variable);
  95. }
  96. return promise.then(function() {
  97. var option = _.findWhere(variable.options, { text: urlValue });
  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.value)) {
  115. variable.current.text = variable.current.value.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. // extract options in comma seperated string
  148. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  149. return { text: text.trim(), value: text.trim() };
  150. });
  151. if (variable.type === 'interval') {
  152. self.updateAutoInterval(variable);
  153. }
  154. if (variable.type === 'custom' && variable.includeAll) {
  155. self.addAllOption(variable);
  156. }
  157. };
  158. this.updateDataSourceVariable = function(variable) {
  159. var options = [];
  160. var sources = datasourceSrv.getMetricSources({skipVariables: true});
  161. var regex;
  162. if (variable.regex) {
  163. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  164. }
  165. for (var i = 0; i < sources.length; i++) {
  166. var source = sources[i];
  167. // must match on type
  168. if (source.meta.id !== variable.query) {
  169. continue;
  170. }
  171. if (regex && !regex.exec(source.name)) {
  172. continue;
  173. }
  174. options.push({text: source.name, value: source.name});
  175. }
  176. if (options.length === 0) {
  177. options.push({text: 'No data sources found', value: ''});
  178. }
  179. variable.options = options;
  180. };
  181. this.updateOptions = function(variable) {
  182. if (variable.type !== 'query') {
  183. self._updateNonQueryVariable(variable);
  184. return self.validateVariableSelectionState(variable);
  185. }
  186. return datasourceSrv.get(variable.datasource)
  187. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  188. .then(_.partial(this.updateTags, variable))
  189. .then(_.partial(this.validateVariableSelectionState, variable));
  190. };
  191. this.selectOptionsForCurrentValue = function(variable) {
  192. var i, y, value, option;
  193. for (i = 0; i < variable.options.length; i++) {
  194. option = variable.options[i];
  195. option.selected = false;
  196. if (_.isArray(variable.current.value)) {
  197. for (y = 0; y < variable.current.value.length; y++) {
  198. value = variable.current.value[y];
  199. if (option.value === value) {
  200. option.selected = true;
  201. }
  202. }
  203. } else if (option.value === variable.current.value) {
  204. option.selected = true;
  205. }
  206. }
  207. };
  208. this.validateVariableSelectionState = function(variable) {
  209. if (!variable.current) {
  210. if (!variable.options.length) { return; }
  211. return self.setVariableValue(variable, variable.options[0], true);
  212. }
  213. if (_.isArray(variable.current.value)) {
  214. self.selectOptionsForCurrentValue(variable);
  215. } else {
  216. var currentOption = _.findWhere(variable.options, {text: variable.current.text});
  217. if (currentOption) {
  218. return self.setVariableValue(variable, currentOption, true);
  219. } else {
  220. if (!variable.options.length) { return; }
  221. return self.setVariableValue(variable, variable.options[0]);
  222. }
  223. }
  224. };
  225. this.updateTags = function(variable, datasource) {
  226. if (variable.useTags) {
  227. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  228. variable.tags = [];
  229. for (var i = 0; i < results.length; i++) {
  230. variable.tags.push(results[i].text);
  231. }
  232. return datasource;
  233. });
  234. } else {
  235. delete variable.tags;
  236. }
  237. return datasource;
  238. };
  239. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  240. return datasource.metricFindQuery(variable.query).then(function (results) {
  241. variable.options = self.metricNamesToVariableValues(variable, results);
  242. if (variable.includeAll) {
  243. self.addAllOption(variable);
  244. }
  245. if (!variable.options.length) {
  246. variable.options.push(getNoneOption());
  247. }
  248. return datasource;
  249. });
  250. };
  251. this.getValuesForTag = function(variable, tagKey) {
  252. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  253. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  254. return datasource.metricFindQuery(query).then(function (results) {
  255. return _.map(results, function(value) {
  256. return value.text;
  257. });
  258. });
  259. });
  260. };
  261. this.metricNamesToVariableValues = function(variable, metricNames) {
  262. var regex, options, i, matches;
  263. options = {}; // use object hash to remove duplicates
  264. if (variable.regex) {
  265. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  266. }
  267. for (i = 0; i < metricNames.length; i++) {
  268. var item = metricNames[i];
  269. var value = item.value || item.text;
  270. var text = item.text || item.value;
  271. if (regex) {
  272. matches = regex.exec(value);
  273. if (!matches) { continue; }
  274. if (matches.length > 1) {
  275. value = matches[1];
  276. text = value;
  277. }
  278. }
  279. options[value] = {text: text, value: value};
  280. }
  281. return _.sortBy(options, 'text');
  282. };
  283. this.addAllOption = function(variable) {
  284. variable.options.unshift({text: 'All', value: "$__all"});
  285. };
  286. });
  287. });