templateValuesSrv.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. self.setVariableValue(variable, variable.options[0]);
  67. }
  68. lock.resolve();
  69. });
  70. }
  71. else if (variable.type === 'interval') {
  72. self.updateAutoInterval(variable);
  73. lock.resolve();
  74. } else {
  75. lock.resolve();
  76. }
  77. });
  78. };
  79. this.setVariableFromUrl = function(variable, urlValue) {
  80. var promise = $q.when(true);
  81. if (variable.refresh) {
  82. promise = this.updateOptions(variable);
  83. }
  84. return promise.then(function() {
  85. var option = _.find(variable.options, function(op) {
  86. return op.text === urlValue || op.value === urlValue;
  87. });
  88. option = option || { text: urlValue, value: urlValue };
  89. self.updateAutoInterval(variable);
  90. return self.setVariableValue(variable, option, true);
  91. });
  92. };
  93. this.updateAutoInterval = function(variable) {
  94. if (!variable.auto) { return; }
  95. // add auto option if missing
  96. if (variable.options.length && variable.options[0].text !== 'auto') {
  97. variable.options.unshift({ text: 'auto', value: '$__auto_interval' });
  98. }
  99. var interval = kbn.calculateInterval(timeSrv.timeRange(), variable.auto_count, (variable.auto_min ? ">"+variable.auto_min : null));
  100. templateSrv.setGrafanaVariable('$__auto_interval', interval);
  101. };
  102. this.setVariableValue = function(variable, option, initPhase) {
  103. variable.current = angular.copy(option);
  104. if (_.isArray(variable.current.text)) {
  105. variable.current.text = variable.current.text.join(' + ');
  106. }
  107. self.selectOptionsForCurrentValue(variable);
  108. templateSrv.updateTemplateData();
  109. // on first load, variable loading is ordered to ensure
  110. // that parents are updated before children.
  111. if (initPhase) {
  112. return $q.when();
  113. }
  114. return self.updateOptionsInChildVariables(variable);
  115. };
  116. this.variableUpdated = function(variable) {
  117. templateSrv.updateTemplateData();
  118. return this.updateOptionsInChildVariables(variable);
  119. };
  120. this.updateOptionsInChildVariables = function(updatedVariable) {
  121. var promises = _.map(self.variables, function(otherVariable) {
  122. if (otherVariable === updatedVariable) {
  123. return;
  124. }
  125. if (templateSrv.containsVariable(otherVariable.query, updatedVariable.name) ||
  126. templateSrv.containsVariable(otherVariable.datasource, updatedVariable.name)) {
  127. return self.updateOptions(otherVariable);
  128. }
  129. });
  130. return $q.all(promises);
  131. };
  132. this._updateNonQueryVariable = function(variable) {
  133. if (variable.type === 'datasource') {
  134. self.updateDataSourceVariable(variable);
  135. return;
  136. }
  137. if (variable.type === 'constant') {
  138. variable.options = [{text: variable.query, value: variable.query}];
  139. return;
  140. }
  141. // extract options in comma separated string
  142. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  143. return { text: text.trim(), value: text.trim() };
  144. });
  145. if (variable.type === 'interval') {
  146. self.updateAutoInterval(variable);
  147. return;
  148. }
  149. if (variable.type === 'custom' && variable.includeAll) {
  150. self.addAllOption(variable);
  151. }
  152. };
  153. this.updateDataSourceVariable = function(variable) {
  154. var options = [];
  155. var sources = datasourceSrv.getMetricSources({skipVariables: true});
  156. var regex;
  157. if (variable.regex) {
  158. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  159. }
  160. for (var i = 0; i < sources.length; i++) {
  161. var source = sources[i];
  162. // must match on type
  163. if (source.meta.id !== variable.query) {
  164. continue;
  165. }
  166. if (regex && !regex.exec(source.name)) {
  167. continue;
  168. }
  169. options.push({text: source.name, value: source.name});
  170. }
  171. if (options.length === 0) {
  172. options.push({text: 'No data sources found', value: ''});
  173. }
  174. variable.options = options;
  175. };
  176. this.updateOptions = function(variable) {
  177. if (variable.type !== 'query') {
  178. self._updateNonQueryVariable(variable);
  179. return self.validateVariableSelectionState(variable);
  180. }
  181. return datasourceSrv.get(variable.datasource)
  182. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  183. .then(_.partial(this.updateTags, variable))
  184. .then(_.partial(this.validateVariableSelectionState, variable));
  185. };
  186. this.selectOptionsForCurrentValue = function(variable) {
  187. var i, y, value, option;
  188. var selected = [];
  189. for (i = 0; i < variable.options.length; i++) {
  190. option = variable.options[i];
  191. option.selected = false;
  192. if (_.isArray(variable.current.value)) {
  193. for (y = 0; y < variable.current.value.length; y++) {
  194. value = variable.current.value[y];
  195. if (option.value === value) {
  196. option.selected = true;
  197. selected.push(option);
  198. }
  199. }
  200. } else if (option.value === variable.current.value) {
  201. option.selected = true;
  202. selected.push(option);
  203. }
  204. }
  205. return selected;
  206. };
  207. this.validateVariableSelectionState = function(variable) {
  208. if (!variable.current) {
  209. if (!variable.options.length) { return; }
  210. return self.setVariableValue(variable, variable.options[0], false);
  211. }
  212. if (_.isArray(variable.current.value)) {
  213. var selected = self.selectOptionsForCurrentValue(variable);
  214. // if none pick first
  215. if (selected.length === 0) {
  216. selected = variable.options[0];
  217. } else {
  218. selected = {
  219. value: _.map(selected, function(val) {return val.value;}),
  220. text: _.map(selected, function(val) {return val.text;}).join(' + '),
  221. };
  222. }
  223. return self.setVariableValue(variable, selected, false);
  224. } else {
  225. var currentOption = _.findWhere(variable.options, {text: variable.current.text});
  226. if (currentOption) {
  227. return self.setVariableValue(variable, currentOption, false);
  228. } else {
  229. if (!variable.options.length) { return $q.when(null); }
  230. return self.setVariableValue(variable, variable.options[0]);
  231. }
  232. }
  233. };
  234. this.updateTags = function(variable, datasource) {
  235. if (variable.useTags) {
  236. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  237. variable.tags = [];
  238. for (var i = 0; i < results.length; i++) {
  239. variable.tags.push(results[i].text);
  240. }
  241. return datasource;
  242. });
  243. } else {
  244. delete variable.tags;
  245. }
  246. return datasource;
  247. };
  248. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  249. return datasource.metricFindQuery(variable.query).then(function (results) {
  250. variable.options = self.metricNamesToVariableValues(variable, results);
  251. if (variable.includeAll) {
  252. self.addAllOption(variable);
  253. }
  254. if (!variable.options.length) {
  255. variable.options.push(getNoneOption());
  256. }
  257. return datasource;
  258. });
  259. };
  260. this.getValuesForTag = function(variable, tagKey) {
  261. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  262. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  263. return datasource.metricFindQuery(query).then(function (results) {
  264. return _.map(results, function(value) {
  265. return value.text;
  266. });
  267. });
  268. });
  269. };
  270. this.metricNamesToVariableValues = function(variable, metricNames) {
  271. var regex, options, i, matches;
  272. options = {}; // use object hash to remove duplicates
  273. if (variable.regex) {
  274. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  275. }
  276. for (i = 0; i < metricNames.length; i++) {
  277. var item = metricNames[i];
  278. var value = item.value || item.text;
  279. var text = item.text || item.value;
  280. if (_.isNumber(value)) {
  281. value = value.toString();
  282. }
  283. if (_.isNumber(text)) {
  284. text = text.toString();
  285. }
  286. if (regex) {
  287. matches = regex.exec(value);
  288. if (!matches) { continue; }
  289. if (matches.length > 1) {
  290. value = matches[1];
  291. text = value;
  292. }
  293. }
  294. options[value] = {text: text, value: value};
  295. }
  296. return _.sortBy(options, 'text');
  297. };
  298. this.addAllOption = function(variable) {
  299. variable.options.unshift({text: 'All', value: "$__all"});
  300. };
  301. });
  302. });