templateValuesSrv.js 8.7 KB

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