templateValuesSrv.js 11 KB

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