templateValuesSrv.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 ((otherVariable.type === "datasource" &&
  138. templateSrv.containsVariable(otherVariable.regex, updatedVariable.name)) ||
  139. templateSrv.containsVariable(otherVariable.query, updatedVariable.name) ||
  140. templateSrv.containsVariable(otherVariable.datasource, updatedVariable.name)) {
  141. return self.updateOptions(otherVariable);
  142. }
  143. });
  144. return $q.all(promises);
  145. };
  146. this._updateNonQueryVariable = function(variable) {
  147. if (variable.type === 'datasource') {
  148. self.updateDataSourceVariable(variable);
  149. return;
  150. }
  151. if (variable.type === 'constant') {
  152. variable.options = [{text: variable.query, value: variable.query}];
  153. return;
  154. }
  155. if (variable.type === 'adhoc') {
  156. variable.current = {};
  157. variable.options = [];
  158. return;
  159. }
  160. // extract options in comma separated string
  161. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  162. return { text: text.trim(), value: text.trim() };
  163. });
  164. if (variable.type === 'interval') {
  165. self.updateAutoInterval(variable);
  166. return;
  167. }
  168. if (variable.type === 'custom' && variable.includeAll) {
  169. self.addAllOption(variable);
  170. }
  171. };
  172. this.updateDataSourceVariable = function(variable) {
  173. var options = [];
  174. var sources = datasourceSrv.getMetricSources({skipVariables: true});
  175. var regex;
  176. if (variable.regex) {
  177. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  178. }
  179. for (var i = 0; i < sources.length; i++) {
  180. var source = sources[i];
  181. // must match on type
  182. if (source.meta.id !== variable.query) {
  183. continue;
  184. }
  185. if (regex && !regex.exec(source.name)) {
  186. continue;
  187. }
  188. options.push({text: source.name, value: source.name});
  189. }
  190. if (options.length === 0) {
  191. options.push({text: 'No data sources found', value: ''});
  192. }
  193. variable.options = options;
  194. };
  195. this.updateOptions = function(variable) {
  196. if (variable.type !== 'query') {
  197. self._updateNonQueryVariable(variable);
  198. return self.validateVariableSelectionState(variable);
  199. }
  200. return datasourceSrv.get(variable.datasource)
  201. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  202. .then(_.partial(this.updateTags, variable))
  203. .then(_.partial(this.validateVariableSelectionState, variable));
  204. };
  205. this.selectOptionsForCurrentValue = function(variable) {
  206. var i, y, value, option;
  207. var selected = [];
  208. for (i = 0; i < variable.options.length; i++) {
  209. option = variable.options[i];
  210. option.selected = false;
  211. if (_.isArray(variable.current.value)) {
  212. for (y = 0; y < variable.current.value.length; y++) {
  213. value = variable.current.value[y];
  214. if (option.value === value) {
  215. option.selected = true;
  216. selected.push(option);
  217. }
  218. }
  219. } else if (option.value === variable.current.value) {
  220. option.selected = true;
  221. selected.push(option);
  222. }
  223. }
  224. return selected;
  225. };
  226. this.validateVariableSelectionState = function(variable) {
  227. if (!variable.current) {
  228. if (!variable.options.length) { return $q.when(); }
  229. return self.setVariableValue(variable, variable.options[0], false);
  230. }
  231. if (_.isArray(variable.current.value)) {
  232. var selected = self.selectOptionsForCurrentValue(variable);
  233. // if none pick first
  234. if (selected.length === 0) {
  235. selected = variable.options[0];
  236. } else {
  237. selected = {
  238. value: _.map(selected, function(val) {return val.value;}),
  239. text: _.map(selected, function(val) {return val.text;}).join(' + '),
  240. };
  241. }
  242. return self.setVariableValue(variable, selected, false);
  243. } else {
  244. var currentOption = _.find(variable.options, {text: variable.current.text});
  245. if (currentOption) {
  246. return self.setVariableValue(variable, currentOption, false);
  247. } else {
  248. if (!variable.options.length) { return $q.when(null); }
  249. return self.setVariableValue(variable, variable.options[0]);
  250. }
  251. }
  252. };
  253. this.updateTags = function(variable, datasource) {
  254. if (variable.useTags) {
  255. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  256. variable.tags = [];
  257. for (var i = 0; i < results.length; i++) {
  258. variable.tags.push(results[i].text);
  259. }
  260. return datasource;
  261. });
  262. } else {
  263. delete variable.tags;
  264. }
  265. return datasource;
  266. };
  267. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  268. return datasource.metricFindQuery(variable.query).then(function (results) {
  269. variable.options = self.metricNamesToVariableValues(variable, results);
  270. if (variable.includeAll) {
  271. self.addAllOption(variable);
  272. }
  273. if (!variable.options.length) {
  274. variable.options.push(getNoneOption());
  275. }
  276. return datasource;
  277. });
  278. };
  279. this.getValuesForTag = function(variable, tagKey) {
  280. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  281. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  282. return datasource.metricFindQuery(query).then(function (results) {
  283. return _.map(results, function(value) {
  284. return value.text;
  285. });
  286. });
  287. });
  288. };
  289. this.metricNamesToVariableValues = function(variable, metricNames) {
  290. var regex, options, i, matches;
  291. options = [];
  292. if (variable.regex) {
  293. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  294. }
  295. for (i = 0; i < metricNames.length; i++) {
  296. var item = metricNames[i];
  297. var value = item.value || item.text;
  298. var text = item.text || item.value;
  299. if (_.isNumber(value)) {
  300. value = value.toString();
  301. }
  302. if (_.isNumber(text)) {
  303. text = text.toString();
  304. }
  305. if (regex) {
  306. matches = regex.exec(value);
  307. if (!matches) { continue; }
  308. if (matches.length > 1) {
  309. value = matches[1];
  310. text = value;
  311. }
  312. }
  313. options.push({text: text, value: value});
  314. }
  315. options = _.uniq(options, 'value');
  316. return this.sortVariableValues(options, variable.sort);
  317. };
  318. this.addAllOption = function(variable) {
  319. variable.options.unshift({text: 'All', value: "$__all"});
  320. };
  321. this.sortVariableValues = function(options, sortOrder) {
  322. if (sortOrder === 0) {
  323. return options;
  324. }
  325. var sortType = Math.ceil(sortOrder / 2);
  326. var reverseSort = (sortOrder % 2 === 0);
  327. if (sortType === 1) {
  328. options = _.sortBy(options, 'text');
  329. } else if (sortType === 2) {
  330. options = _.sortBy(options, function(opt) {
  331. var matches = opt.text.match(/.*?(\d+).*/);
  332. if (!matches) {
  333. return 0;
  334. } else {
  335. return parseInt(matches[1], 10);
  336. }
  337. });
  338. }
  339. if (reverseSort) {
  340. options = options.reverse();
  341. }
  342. return options;
  343. };
  344. });
  345. });