templateValuesSrv.js 13 KB

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