templateValuesSrv.js 8.9 KB

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