templateValuesSrv.js 9.0 KB

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