variable_srv.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import angular from 'angular';
  2. import _ from 'lodash';
  3. import coreModule from 'app/core/core_module';
  4. import { variableTypes } from './variable';
  5. import { Graph } from 'app/core/utils/dag';
  6. export class VariableSrv {
  7. dashboard: any;
  8. variables: any;
  9. /** @ngInject */
  10. constructor(private $rootScope, private $q, private $location, private $injector, private templateSrv) {
  11. // update time variant variables
  12. $rootScope.$on('refresh', this.onDashboardRefresh.bind(this), $rootScope);
  13. $rootScope.$on('template-variable-value-updated', this.updateUrlParamsWithCurrentVariables.bind(this), $rootScope);
  14. }
  15. init(dashboard) {
  16. this.dashboard = dashboard;
  17. // create working class models representing variables
  18. this.variables = dashboard.templating.list = dashboard.templating.list.map(this.createVariableFromModel.bind(this));
  19. this.templateSrv.init(this.variables);
  20. // init variables
  21. for (const variable of this.variables) {
  22. variable.initLock = this.$q.defer();
  23. }
  24. const queryParams = this.$location.search();
  25. return this.$q
  26. .all(
  27. this.variables.map(variable => {
  28. return this.processVariable(variable, queryParams);
  29. })
  30. )
  31. .then(() => {
  32. this.templateSrv.updateTemplateData();
  33. });
  34. }
  35. onDashboardRefresh(evt, payload) {
  36. if (payload && payload.fromVariableValueUpdated) {
  37. return Promise.resolve({});
  38. }
  39. const promises = this.variables.filter(variable => variable.refresh === 2).map(variable => {
  40. const previousOptions = variable.options.slice();
  41. return variable.updateOptions().then(() => {
  42. if (angular.toJson(previousOptions) !== angular.toJson(variable.options)) {
  43. this.$rootScope.$emit('template-variable-value-updated');
  44. }
  45. });
  46. });
  47. return this.$q.all(promises);
  48. }
  49. processVariable(variable, queryParams) {
  50. const dependencies = [];
  51. for (const otherVariable of this.variables) {
  52. if (variable.dependsOn(otherVariable)) {
  53. dependencies.push(otherVariable.initLock.promise);
  54. }
  55. }
  56. return this.$q
  57. .all(dependencies)
  58. .then(() => {
  59. const urlValue = queryParams['var-' + variable.name];
  60. if (urlValue !== void 0) {
  61. return variable.setValueFromUrl(urlValue).then(variable.initLock.resolve);
  62. }
  63. if (variable.refresh === 1 || variable.refresh === 2) {
  64. return variable.updateOptions().then(variable.initLock.resolve);
  65. }
  66. variable.initLock.resolve();
  67. })
  68. .finally(() => {
  69. this.templateSrv.variableInitialized(variable);
  70. delete variable.initLock;
  71. });
  72. }
  73. createVariableFromModel(model) {
  74. const ctor = variableTypes[model.type].ctor;
  75. if (!ctor) {
  76. throw {
  77. message: 'Unable to find variable constructor for ' + model.type,
  78. };
  79. }
  80. const variable = this.$injector.instantiate(ctor, { model: model });
  81. return variable;
  82. }
  83. addVariable(variable) {
  84. this.variables.push(variable);
  85. this.templateSrv.updateTemplateData();
  86. this.dashboard.updateSubmenuVisibility();
  87. }
  88. removeVariable(variable) {
  89. const index = _.indexOf(this.variables, variable);
  90. this.variables.splice(index, 1);
  91. this.templateSrv.updateTemplateData();
  92. this.dashboard.updateSubmenuVisibility();
  93. }
  94. updateOptions(variable) {
  95. return variable.updateOptions();
  96. }
  97. variableUpdated(variable, emitChangeEvents?) {
  98. // if there is a variable lock ignore cascading update because we are in a boot up scenario
  99. if (variable.initLock) {
  100. return this.$q.when();
  101. }
  102. const g = this.createGraph();
  103. const promises = g
  104. .getNode(variable.name)
  105. .getOptimizedInputEdges()
  106. .map(e => {
  107. return this.updateOptions(this.variables.find(v => v.name === e.inputNode.name));
  108. });
  109. return this.$q.all(promises).then(() => {
  110. if (emitChangeEvents) {
  111. this.$rootScope.$emit('template-variable-value-updated');
  112. this.$rootScope.$broadcast('refresh', { fromVariableValueUpdated: true });
  113. }
  114. });
  115. }
  116. selectOptionsForCurrentValue(variable) {
  117. var i, y, value, option;
  118. const selected: any = [];
  119. for (i = 0; i < variable.options.length; i++) {
  120. option = variable.options[i];
  121. option.selected = false;
  122. if (_.isArray(variable.current.value)) {
  123. for (y = 0; y < variable.current.value.length; y++) {
  124. value = variable.current.value[y];
  125. if (option.value === value) {
  126. option.selected = true;
  127. selected.push(option);
  128. }
  129. }
  130. } else if (option.value === variable.current.value) {
  131. option.selected = true;
  132. selected.push(option);
  133. }
  134. }
  135. return selected;
  136. }
  137. validateVariableSelectionState(variable) {
  138. if (!variable.current) {
  139. variable.current = {};
  140. }
  141. if (_.isArray(variable.current.value)) {
  142. var selected = this.selectOptionsForCurrentValue(variable);
  143. // if none pick first
  144. if (selected.length === 0) {
  145. selected = variable.options[0];
  146. } else {
  147. selected = {
  148. value: _.map(selected, function(val) {
  149. return val.value;
  150. }),
  151. text: _.map(selected, function(val) {
  152. return val.text;
  153. }).join(' + '),
  154. };
  155. }
  156. return variable.setValue(selected);
  157. } else {
  158. const currentOption = _.find(variable.options, {
  159. text: variable.current.text,
  160. });
  161. if (currentOption) {
  162. return variable.setValue(currentOption);
  163. } else {
  164. if (!variable.options.length) {
  165. return Promise.resolve();
  166. }
  167. return variable.setValue(variable.options[0]);
  168. }
  169. }
  170. }
  171. setOptionFromUrl(variable, urlValue) {
  172. var promise = this.$q.when();
  173. if (variable.refresh) {
  174. promise = variable.updateOptions();
  175. }
  176. return promise.then(() => {
  177. var option = _.find(variable.options, op => {
  178. return op.text === urlValue || op.value === urlValue;
  179. });
  180. let defaultText = urlValue;
  181. const defaultValue = urlValue;
  182. if (!option && _.isArray(urlValue)) {
  183. defaultText = [];
  184. for (let n = 0; n < urlValue.length; n++) {
  185. const t = _.find(variable.options, op => {
  186. return op.value === urlValue[n];
  187. });
  188. if (t) {
  189. defaultText.push(t.text);
  190. }
  191. }
  192. }
  193. option = option || { text: defaultText, value: defaultValue };
  194. return variable.setValue(option);
  195. });
  196. }
  197. setOptionAsCurrent(variable, option) {
  198. variable.current = _.cloneDeep(option);
  199. if (_.isArray(variable.current.text)) {
  200. variable.current.text = variable.current.text.join(' + ');
  201. }
  202. this.selectOptionsForCurrentValue(variable);
  203. return this.variableUpdated(variable);
  204. }
  205. updateUrlParamsWithCurrentVariables() {
  206. // update url
  207. const params = this.$location.search();
  208. // remove variable params
  209. _.each(params, function(value, key) {
  210. if (key.indexOf('var-') === 0) {
  211. delete params[key];
  212. }
  213. });
  214. // add new values
  215. this.templateSrv.fillVariableValuesForUrl(params);
  216. // update url
  217. this.$location.search(params);
  218. }
  219. setAdhocFilter(options) {
  220. var variable = _.find(this.variables, {
  221. type: 'adhoc',
  222. datasource: options.datasource,
  223. });
  224. if (!variable) {
  225. variable = this.createVariableFromModel({
  226. name: 'Filters',
  227. type: 'adhoc',
  228. datasource: options.datasource,
  229. });
  230. this.addVariable(variable);
  231. }
  232. const filters = variable.filters;
  233. let filter = _.find(filters, { key: options.key, value: options.value });
  234. if (!filter) {
  235. filter = { key: options.key, value: options.value };
  236. filters.push(filter);
  237. }
  238. filter.operator = options.operator;
  239. this.variableUpdated(variable, true);
  240. }
  241. createGraph() {
  242. const g = new Graph();
  243. this.variables.forEach(v1 => {
  244. g.createNode(v1.name);
  245. this.variables.forEach(v2 => {
  246. if (v1 === v2) {
  247. return;
  248. }
  249. if (v1.dependsOn(v2)) {
  250. g.link(v1.name, v2.name);
  251. }
  252. });
  253. });
  254. return g;
  255. }
  256. }
  257. coreModule.service('variableSrv', VariableSrv);