templateValuesSrv.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. $rootScope.onAppEvent('time-range-changed', function() {
  13. var variable = _.findWhere(self.variables, { type: 'interval' });
  14. if (variable) {
  15. self.updateAutoInterval(variable);
  16. }
  17. }, $rootScope);
  18. this.init = function(dashboard) {
  19. this.variables = dashboard.templating.list;
  20. templateSrv.init(this.variables);
  21. var queryParams = $location.search();
  22. var promises = [];
  23. for (var i = 0; i < this.variables.length; i++) {
  24. var variable = this.variables[i];
  25. var urlValue = queryParams['var-' + variable.name];
  26. if (urlValue !== void 0) {
  27. promises.push(this.setVariableFromUrl(variable, urlValue));
  28. }
  29. else if (variable.refresh) {
  30. promises.push(this.updateOptions(variable));
  31. }
  32. else if (variable.type === 'interval') {
  33. this.updateAutoInterval(variable);
  34. }
  35. }
  36. return $q.all(promises);
  37. };
  38. this.setVariableFromUrl = function(variable, urlValue) {
  39. if (variable.refresh) {
  40. var self = this;
  41. //refresh the list of options before setting the value
  42. return this.updateOptions(variable).then(function() {
  43. var option = _.findWhere(variable.options, { text: urlValue });
  44. option = option || { text: urlValue, value: urlValue };
  45. self.updateAutoInterval(variable);
  46. return self.setVariableValue(variable, option);
  47. });
  48. }
  49. var option = _.findWhere(variable.options, { text: urlValue });
  50. option = option || { text: urlValue, value: urlValue };
  51. this.updateAutoInterval(variable);
  52. return this.setVariableValue(variable, option);
  53. };
  54. this.updateAutoInterval = function(variable) {
  55. if (!variable.auto) { return; }
  56. // add auto option if missing
  57. if (variable.options.length && variable.options[0].text !== 'auto') {
  58. variable.options.unshift({ text: 'auto', value: '$__auto_interval' });
  59. }
  60. var interval = kbn.calculateInterval(timeSrv.timeRange(), variable.auto_count);
  61. templateSrv.setGrafanaVariable('$__auto_interval', interval);
  62. };
  63. this.setVariableValue = function(variable, option) {
  64. variable.current = angular.copy(option);
  65. if (_.isArray(variable.current.value)) {
  66. variable.current.text = variable.current.value.join(' + ');
  67. }
  68. self.selectOptionsForCurrentValue(variable);
  69. templateSrv.updateTemplateData();
  70. return self.updateOptionsInChildVariables(variable);
  71. };
  72. this.variableUpdated = function(variable) {
  73. templateSrv.updateTemplateData();
  74. return this.updateOptionsInChildVariables(variable);
  75. };
  76. this.updateOptionsInChildVariables = function(updatedVariable) {
  77. var promises = _.map(self.variables, function(otherVariable) {
  78. if (otherVariable === updatedVariable) {
  79. return;
  80. }
  81. if (templateSrv.containsVariable(otherVariable.query, updatedVariable.name)) {
  82. return self.updateOptions(otherVariable);
  83. }
  84. });
  85. return $q.all(promises);
  86. };
  87. this._updateNonQueryVariable = function(variable) {
  88. // extract options in comma seperated string
  89. variable.options = _.map(variable.query.split(/[,]+/), function(text) {
  90. return { text: text.trim(), value: text.trim() };
  91. });
  92. if (variable.type === 'interval') {
  93. self.updateAutoInterval(variable);
  94. }
  95. if (variable.type === 'custom' && variable.includeAll) {
  96. self.addAllOption(variable);
  97. }
  98. };
  99. this.updateOptions = function(variable) {
  100. if (variable.type !== 'query') {
  101. self._updateNonQueryVariable(variable);
  102. self.setVariableValue(variable, variable.options[0]);
  103. return $q.when([]);
  104. }
  105. return datasourceSrv.get(variable.datasource)
  106. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  107. .then(_.partial(this.updateTags, variable))
  108. .then(_.partial(this.validateVariableSelectionState, variable));
  109. };
  110. this.selectOptionsForCurrentValue = function(variable) {
  111. var i, y, value, option;
  112. for (i = 0; i < variable.options.length; i++) {
  113. option = variable.options[i];
  114. option.selected = false;
  115. if (_.isArray(variable.current.value)) {
  116. for (y = 0; y < variable.current.value.length; y++) {
  117. value = variable.current.value[y];
  118. if (option.value === value) {
  119. option.selected = true;
  120. }
  121. }
  122. } else if (option.value === variable.current.value) {
  123. option.selected = true;
  124. }
  125. }
  126. };
  127. this.validateVariableSelectionState = function(variable) {
  128. if (!variable.current) {
  129. if (!variable.options.length) { return; }
  130. return self.setVariableValue(variable, variable.options[0]);
  131. }
  132. if (_.isArray(variable.current.value)) {
  133. self.selectOptionsForCurrentValue(variable);
  134. } else {
  135. var currentOption = _.findWhere(variable.options, { text: variable.current.text });
  136. if (currentOption) {
  137. return self.setVariableValue(variable, currentOption);
  138. } else {
  139. if (!variable.options.length) { return; }
  140. return self.setVariableValue(variable, variable.options[0]);
  141. }
  142. }
  143. };
  144. this.updateTags = function(variable, datasource) {
  145. if (variable.useTags) {
  146. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  147. variable.tags = [];
  148. for (var i = 0; i < results.length; i++) {
  149. variable.tags.push(results[i].text);
  150. }
  151. return datasource;
  152. });
  153. } else {
  154. delete variable.tags;
  155. }
  156. return datasource;
  157. };
  158. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  159. return datasource.metricFindQuery(variable.query).then(function (results) {
  160. variable.options = self.metricNamesToVariableValues(variable, results);
  161. if (variable.includeAll) {
  162. self.addAllOption(variable);
  163. }
  164. if (!variable.options.length) {
  165. variable.options.push(getNoneOption());
  166. }
  167. return datasource;
  168. });
  169. };
  170. this.getValuesForTag = function(variable, tagKey) {
  171. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  172. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  173. return datasource.metricFindQuery(query).then(function (results) {
  174. return _.map(results, function(value) {
  175. return value.text;
  176. });
  177. });
  178. });
  179. };
  180. this.metricNamesToVariableValues = function(variable, metricNames) {
  181. var regex, options, i, matches;
  182. options = {}; // use object hash to remove duplicates
  183. if (variable.regex) {
  184. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  185. }
  186. for (i = 0; i < metricNames.length; i++) {
  187. var value = metricNames[i].text;
  188. if (regex) {
  189. matches = regex.exec(value);
  190. if (!matches) { continue; }
  191. if (matches.length > 1) {
  192. value = matches[1];
  193. }
  194. }
  195. options[value] = value;
  196. }
  197. return _.map(_.keys(options).sort(), function(key) {
  198. var option = { text: key, value: key };
  199. // check if values need to be regex escaped
  200. if (self.shouldRegexEscape(variable)) {
  201. option.value = self.regexEscape(option.value);
  202. }
  203. return option;
  204. });
  205. };
  206. this.shouldRegexEscape = function(variable) {
  207. return (variable.includeAll || variable.multi) && variable.allFormat.indexOf('regex') !== -1;
  208. };
  209. this.regexEscape = function(value) {
  210. return value.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
  211. };
  212. this.addAllOption = function(variable) {
  213. var allValue = '';
  214. switch(variable.allFormat) {
  215. case 'wildcard': {
  216. allValue = '*';
  217. break;
  218. }
  219. case 'regex wildcard': {
  220. allValue = '.*';
  221. break;
  222. }
  223. case 'lucene': {
  224. var quotedValues = _.map(variable.options, function(val) {
  225. return '\\\"' + val.text + '\\\"';
  226. });
  227. allValue = '(' + quotedValues.join(' OR ') + ')';
  228. break;
  229. }
  230. case 'regex values': {
  231. allValue = '(' + _.map(variable.options, function(option) {
  232. return self.regexEscape(option.text);
  233. }).join('|') + ')';
  234. break;
  235. }
  236. case 'pipe': {
  237. allValue = _.pluck(variable.options, 'text').join('|');
  238. break;
  239. }
  240. default: {
  241. allValue = '{';
  242. allValue += _.pluck(variable.options, 'text').join(',');
  243. allValue += '}';
  244. }
  245. }
  246. variable.options.unshift({text: 'All', value: allValue});
  247. };
  248. });
  249. });