templateValuesSrv.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. // extract options in comma seperated string
  138. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  139. return { text: text.trim(), value: text.trim() };
  140. });
  141. if (variable.type === 'interval') {
  142. self.updateAutoInterval(variable);
  143. }
  144. if (variable.type === 'custom' && variable.includeAll) {
  145. self.addAllOption(variable);
  146. }
  147. };
  148. this.updateDataSourceVariable = function(variable) {
  149. var options = [];
  150. var sources = datasourceSrv.getMetricSources({skipVariables: true});
  151. var regex;
  152. if (variable.regex) {
  153. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  154. }
  155. for (var i = 0; i < sources.length; i++) {
  156. var source = sources[i];
  157. // must match on type
  158. if (source.meta.id !== variable.query) {
  159. continue;
  160. }
  161. if (regex && !regex.exec(source.name)) {
  162. continue;
  163. }
  164. options.push({text: source.name, value: source.name});
  165. }
  166. if (options.length === 0) {
  167. options.push({text: 'No data sources found', value: ''});
  168. }
  169. variable.options = options;
  170. };
  171. this.updateOptions = function(variable) {
  172. if (variable.type !== 'query') {
  173. self._updateNonQueryVariable(variable);
  174. return self.validateVariableSelectionState(variable);
  175. }
  176. return datasourceSrv.get(variable.datasource)
  177. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  178. .then(_.partial(this.updateTags, variable))
  179. .then(_.partial(this.validateVariableSelectionState, variable));
  180. };
  181. this.selectOptionsForCurrentValue = function(variable) {
  182. var i, y, value, option;
  183. var selected = [];
  184. for (i = 0; i < variable.options.length; i++) {
  185. option = variable.options[i];
  186. option.selected = false;
  187. if (_.isArray(variable.current.value)) {
  188. for (y = 0; y < variable.current.value.length; y++) {
  189. value = variable.current.value[y];
  190. if (option.value === value) {
  191. option.selected = true;
  192. selected.push(option);
  193. }
  194. }
  195. } else if (option.value === variable.current.value) {
  196. option.selected = true;
  197. selected.push(option);
  198. }
  199. }
  200. return selected;
  201. };
  202. this.validateVariableSelectionState = function(variable) {
  203. if (!variable.current) {
  204. if (!variable.options.length) { return; }
  205. return self.setVariableValue(variable, variable.options[0], false);
  206. }
  207. if (_.isArray(variable.current.value)) {
  208. var selected = self.selectOptionsForCurrentValue(variable);
  209. // if none pick first
  210. if (selected.length === 0) {
  211. selected = variable.options[0];
  212. } else {
  213. selected = {
  214. value: _.map(selected, function(val) {return val.value;}),
  215. text: _.map(selected, function(val) {return val.text;}).join(' + '),
  216. };
  217. }
  218. return self.setVariableValue(variable, selected, false);
  219. } else {
  220. var currentOption = _.findWhere(variable.options, {text: variable.current.text});
  221. if (currentOption) {
  222. return self.setVariableValue(variable, currentOption, false);
  223. } else {
  224. if (!variable.options.length) { return; }
  225. return self.setVariableValue(variable, variable.options[0]);
  226. }
  227. }
  228. };
  229. this.updateTags = function(variable, datasource) {
  230. if (variable.useTags) {
  231. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  232. variable.tags = [];
  233. for (var i = 0; i < results.length; i++) {
  234. variable.tags.push(results[i].text);
  235. }
  236. return datasource;
  237. });
  238. } else {
  239. delete variable.tags;
  240. }
  241. return datasource;
  242. };
  243. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  244. return datasource.metricFindQuery(variable.query).then(function (results) {
  245. variable.options = self.metricNamesToVariableValues(variable, results);
  246. if (variable.includeAll) {
  247. self.addAllOption(variable);
  248. }
  249. if (!variable.options.length) {
  250. variable.options.push(getNoneOption());
  251. }
  252. return datasource;
  253. });
  254. };
  255. this.getValuesForTag = function(variable, tagKey) {
  256. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  257. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  258. return datasource.metricFindQuery(query).then(function (results) {
  259. return _.map(results, function(value) {
  260. return value.text;
  261. });
  262. });
  263. });
  264. };
  265. this.metricNamesToVariableValues = function(variable, metricNames) {
  266. var regex, options, i, matches;
  267. options = {}; // use object hash to remove duplicates
  268. if (variable.regex) {
  269. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  270. }
  271. for (i = 0; i < metricNames.length; i++) {
  272. var item = metricNames[i];
  273. var value = item.value || item.text;
  274. var text = item.text || item.value;
  275. if (_.isNumber(value)) {
  276. value = value.toString();
  277. }
  278. if (_.isNumber(text)) {
  279. text = text.toString();
  280. }
  281. if (regex) {
  282. matches = regex.exec(value);
  283. if (!matches) { continue; }
  284. if (matches.length > 1) {
  285. value = matches[1];
  286. text = value;
  287. }
  288. }
  289. options[value] = {text: text, value: value};
  290. }
  291. return _.sortBy(options, 'text');
  292. };
  293. this.addAllOption = function(variable) {
  294. variable.options.unshift({text: 'All', value: "$__all"});
  295. };
  296. });
  297. });