templateValuesSrv.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. if (templateSrv.containsVariable(variable.query, v.name)) {
  52. dependencies.push(self.variableLock[v.name].promise);
  53. }
  54. });
  55. }
  56. return $q.all(dependencies).then(function() {
  57. var urlValue = queryParams['var-' + variable.name];
  58. if (urlValue !== void 0) {
  59. return self.setVariableFromUrl(variable, urlValue).then(lock.resolve);
  60. }
  61. else if (variable.refresh === 1 || variable.refresh === 2) {
  62. return self.updateOptions(variable).then(function() {
  63. if (_.isEmpty(variable.current) && variable.options.length) {
  64. console.log("setting current for %s", variable.name);
  65. self.setVariableValue(variable, variable.options[0]);
  66. }
  67. lock.resolve();
  68. });
  69. }
  70. else if (variable.type === 'interval') {
  71. self.updateAutoInterval(variable);
  72. lock.resolve();
  73. } else {
  74. lock.resolve();
  75. }
  76. });
  77. };
  78. this.setVariableFromUrl = function(variable, urlValue) {
  79. var promise = $q.when(true);
  80. if (variable.refresh) {
  81. promise = this.updateOptions(variable);
  82. }
  83. return promise.then(function() {
  84. var option = _.findWhere(variable.options, { text: urlValue });
  85. option = option || { text: urlValue, value: urlValue };
  86. self.updateAutoInterval(variable);
  87. return self.setVariableValue(variable, option, true);
  88. });
  89. };
  90. this.updateAutoInterval = function(variable) {
  91. if (!variable.auto) { return; }
  92. // add auto option if missing
  93. if (variable.options.length && variable.options[0].text !== 'auto') {
  94. variable.options.unshift({ text: 'auto', value: '$__auto_interval' });
  95. }
  96. var interval = kbn.calculateInterval(timeSrv.timeRange(), variable.auto_count, (variable.auto_min ? ">"+variable.auto_min : null));
  97. templateSrv.setGrafanaVariable('$__auto_interval', interval);
  98. };
  99. this.setVariableValue = function(variable, option, initPhase) {
  100. variable.current = angular.copy(option);
  101. if (_.isArray(variable.current.value)) {
  102. variable.current.text = variable.current.value.join(' + ');
  103. }
  104. self.selectOptionsForCurrentValue(variable);
  105. templateSrv.updateTemplateData();
  106. // on first load, variable loading is ordered to ensure
  107. // that parents are updated before children.
  108. if (initPhase) {
  109. return $q.when();
  110. }
  111. return self.updateOptionsInChildVariables(variable);
  112. };
  113. this.variableUpdated = function(variable) {
  114. templateSrv.updateTemplateData();
  115. return this.updateOptionsInChildVariables(variable);
  116. };
  117. this.updateOptionsInChildVariables = function(updatedVariable) {
  118. var promises = _.map(self.variables, function(otherVariable) {
  119. if (otherVariable === updatedVariable) {
  120. return;
  121. }
  122. if (templateSrv.containsVariable(otherVariable.query, updatedVariable.name)) {
  123. return self.updateOptions(otherVariable);
  124. }
  125. });
  126. return $q.all(promises);
  127. };
  128. this._updateNonQueryVariable = function(variable) {
  129. // extract options in comma seperated string
  130. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  131. return { text: text.trim(), value: text.trim() };
  132. });
  133. if (variable.type === 'interval') {
  134. self.updateAutoInterval(variable);
  135. }
  136. if (variable.type === 'custom' && variable.includeAll) {
  137. self.addAllOption(variable);
  138. }
  139. };
  140. this.updateOptions = function(variable) {
  141. if (variable.type !== 'query') {
  142. self._updateNonQueryVariable(variable);
  143. self.setVariableValue(variable, variable.options[0]);
  144. return $q.when([]);
  145. }
  146. return datasourceSrv.get(variable.datasource)
  147. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  148. .then(_.partial(this.updateTags, variable))
  149. .then(_.partial(this.validateVariableSelectionState, variable));
  150. };
  151. this.selectOptionsForCurrentValue = function(variable) {
  152. var i, y, value, option;
  153. for (i = 0; i < variable.options.length; i++) {
  154. option = variable.options[i];
  155. option.selected = false;
  156. if (_.isArray(variable.current.value)) {
  157. for (y = 0; y < variable.current.value.length; y++) {
  158. value = variable.current.value[y];
  159. if (option.value === value) {
  160. option.selected = true;
  161. }
  162. }
  163. } else if (option.value === variable.current.value) {
  164. option.selected = true;
  165. }
  166. }
  167. };
  168. this.validateVariableSelectionState = function(variable) {
  169. if (!variable.current) {
  170. if (!variable.options.length) { return; }
  171. return self.setVariableValue(variable, variable.options[0], true);
  172. }
  173. if (_.isArray(variable.current.value)) {
  174. self.selectOptionsForCurrentValue(variable);
  175. } else {
  176. var currentOption = _.findWhere(variable.options, { text: variable.current.text });
  177. if (currentOption) {
  178. return self.setVariableValue(variable, currentOption, true);
  179. } else {
  180. if (!variable.options.length) { return; }
  181. return self.setVariableValue(variable, variable.options[0]);
  182. }
  183. }
  184. };
  185. this.updateTags = function(variable, datasource) {
  186. if (variable.useTags) {
  187. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  188. variable.tags = [];
  189. for (var i = 0; i < results.length; i++) {
  190. variable.tags.push(results[i].text);
  191. }
  192. return datasource;
  193. });
  194. } else {
  195. delete variable.tags;
  196. }
  197. return datasource;
  198. };
  199. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  200. return datasource.metricFindQuery(variable.query).then(function (results) {
  201. variable.options = self.metricNamesToVariableValues(variable, results);
  202. if (variable.includeAll) {
  203. self.addAllOption(variable);
  204. }
  205. if (!variable.options.length) {
  206. variable.options.push(getNoneOption());
  207. }
  208. return datasource;
  209. });
  210. };
  211. this.getValuesForTag = function(variable, tagKey) {
  212. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  213. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  214. return datasource.metricFindQuery(query).then(function (results) {
  215. return _.map(results, function(value) {
  216. return value.text;
  217. });
  218. });
  219. });
  220. };
  221. this.metricNamesToVariableValues = function(variable, metricNames) {
  222. var regex, options, i, matches;
  223. options = {}; // use object hash to remove duplicates
  224. if (variable.regex) {
  225. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  226. }
  227. for (i = 0; i < metricNames.length; i++) {
  228. var item = metricNames[i];
  229. var value = item.value || item.text;
  230. var text = item.text || item.value;
  231. if (regex) {
  232. matches = regex.exec(value);
  233. if (!matches) { continue; }
  234. if (matches.length > 1) {
  235. value = matches[1];
  236. text = value;
  237. }
  238. }
  239. options[value] = {text: text, value: value};
  240. }
  241. return _.map(_.keys(options).sort(), function(key) {
  242. return options[key];
  243. });
  244. };
  245. this.addAllOption = function(variable) {
  246. if (variable.allValue) {
  247. variable.options.unshift({text: 'All', value: variable.allValue});
  248. return;
  249. }
  250. variable.options.unshift({text: 'All', value: "$__all"});
  251. };
  252. });
  253. });