templateValuesSrv.js 11 KB

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