templateValuesSrv.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. define([
  2. 'angular',
  3. 'lodash',
  4. '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. });
  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. };
  96. this.updateOptions = function(variable) {
  97. if (variable.type !== 'query') {
  98. self._updateNonQueryVariable(variable);
  99. self.setVariableValue(variable, variable.options[0]);
  100. return $q.when([]);
  101. }
  102. return datasourceSrv.get(variable.datasource)
  103. .then(_.partial(this.updateOptionsFromMetricFindQuery, variable))
  104. .then(_.partial(this.updateTags, variable))
  105. .then(_.partial(this.validateVariableSelectionState, variable));
  106. };
  107. this.selectOptionsForCurrentValue = function(variable) {
  108. var i, y, value, option;
  109. for (i = 0; i < variable.options.length; i++) {
  110. option = variable.options[i];
  111. option.selected = false;
  112. if (_.isArray(variable.current.value)) {
  113. for (y = 0; y < variable.current.value.length; y++) {
  114. value = variable.current.value[i];
  115. if (option.value === value) {
  116. option.selected = true;
  117. }
  118. }
  119. } else if (option.value === variable.current.value) {
  120. option.selected = true;
  121. }
  122. }
  123. };
  124. this.validateVariableSelectionState = function(variable) {
  125. if (!variable.current) {
  126. if (!variable.options.length) { return; }
  127. return self.setVariableValue(variable, variable.options[0]);
  128. }
  129. if (_.isArray(variable.current.value)) {
  130. self.selectOptionsForCurrentValue(variable);
  131. } else {
  132. var currentOption = _.findWhere(variable.options, { text: variable.current.text });
  133. if (currentOption) {
  134. return self.setVariableValue(variable, currentOption);
  135. } else {
  136. if (!variable.options.length) { return; }
  137. return self.setVariableValue(variable, variable.options[0]);
  138. }
  139. }
  140. };
  141. this.updateTags = function(variable, datasource) {
  142. if (variable.useTags) {
  143. return datasource.metricFindQuery(variable.tagsQuery).then(function (results) {
  144. variable.tags = [];
  145. for (var i = 0; i < results.length; i++) {
  146. variable.tags.push(results[i].text);
  147. }
  148. return datasource;
  149. });
  150. } else {
  151. delete variable.tags;
  152. }
  153. return datasource;
  154. };
  155. this.updateOptionsFromMetricFindQuery = function(variable, datasource) {
  156. return datasource.metricFindQuery(variable.query).then(function (results) {
  157. variable.options = self.metricNamesToVariableValues(variable, results);
  158. if (variable.includeAll) {
  159. self.addAllOption(variable);
  160. }
  161. if (!variable.options.length) {
  162. variable.options.push(getNoneOption());
  163. }
  164. return datasource;
  165. });
  166. };
  167. this.getValuesForTag = function(variable, tagKey) {
  168. return datasourceSrv.get(variable.datasource).then(function(datasource) {
  169. var query = variable.tagValuesQuery.replace('$tag', tagKey);
  170. return datasource.metricFindQuery(query).then(function (results) {
  171. return _.map(results, function(value) {
  172. return value.text;
  173. });
  174. });
  175. });
  176. };
  177. this.metricNamesToVariableValues = function(variable, metricNames) {
  178. var regex, options, i, matches;
  179. options = {}; // use object hash to remove duplicates
  180. if (variable.regex) {
  181. regex = kbn.stringToJsRegex(templateSrv.replace(variable.regex));
  182. }
  183. for (i = 0; i < metricNames.length; i++) {
  184. var value = metricNames[i].text;
  185. if (regex) {
  186. matches = regex.exec(value);
  187. if (!matches) { continue; }
  188. if (matches.length > 1) {
  189. value = matches[1];
  190. }
  191. }
  192. options[value] = value;
  193. }
  194. return _.map(_.keys(options).sort(), function(key) {
  195. var option = { text: key, value: key };
  196. // check if values need to be regex escaped
  197. if (self.shouldRegexEscape(variable)) {
  198. option.value = self.regexEscape(option.value);
  199. }
  200. return option;
  201. });
  202. };
  203. this.shouldRegexEscape = function(variable) {
  204. return (variable.includeAll || variable.multi) && variable.allFormat.indexOf('regex') !== -1;
  205. };
  206. this.regexEscape = function(value) {
  207. return value.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
  208. };
  209. this.addAllOption = function(variable) {
  210. var allValue = '';
  211. switch(variable.allFormat) {
  212. case 'wildcard':
  213. allValue = '*';
  214. break;
  215. case 'regex wildcard':
  216. allValue = '.*';
  217. break;
  218. case 'regex values':
  219. allValue = '(' + _.map(variable.options, function(option) {
  220. return self.regexEscape(option.text);
  221. }).join('|') + ')';
  222. break;
  223. default:
  224. allValue = '{';
  225. allValue += _.pluck(variable.options, 'text').join(',');
  226. allValue += '}';
  227. }
  228. variable.options.unshift({text: 'All', value: allValue});
  229. };
  230. });
  231. });