variable_srv.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 node = g.getNode(variable.name);
  104. let promises = [];
  105. if (node) {
  106. promises = node.getOptimizedInputEdges().map(e => {
  107. return this.updateOptions(this.variables.find(v => v.name === e.inputNode.name));
  108. });
  109. }
  110. return this.$q.all(promises).then(() => {
  111. if (emitChangeEvents) {
  112. this.$rootScope.$emit('template-variable-value-updated');
  113. this.$rootScope.$broadcast('refresh', { fromVariableValueUpdated: true });
  114. }
  115. });
  116. }
  117. selectOptionsForCurrentValue(variable) {
  118. let i, y, value, option;
  119. const selected: any = [];
  120. for (i = 0; i < variable.options.length; i++) {
  121. option = variable.options[i];
  122. option.selected = false;
  123. if (_.isArray(variable.current.value)) {
  124. for (y = 0; y < variable.current.value.length; y++) {
  125. value = variable.current.value[y];
  126. if (option.value === value) {
  127. option.selected = true;
  128. selected.push(option);
  129. }
  130. }
  131. } else if (option.value === variable.current.value) {
  132. option.selected = true;
  133. selected.push(option);
  134. }
  135. }
  136. return selected;
  137. }
  138. validateVariableSelectionState(variable) {
  139. if (!variable.current) {
  140. variable.current = {};
  141. }
  142. if (_.isArray(variable.current.value)) {
  143. let selected = this.selectOptionsForCurrentValue(variable);
  144. // if none pick first
  145. if (selected.length === 0) {
  146. selected = variable.options[0];
  147. } else {
  148. selected = {
  149. value: _.map(selected, val => {
  150. return val.value;
  151. }),
  152. text: _.map(selected, val => {
  153. return val.text;
  154. }).join(' + '),
  155. };
  156. }
  157. return variable.setValue(selected);
  158. } else {
  159. const currentOption = _.find(variable.options, {
  160. text: variable.current.text,
  161. });
  162. if (currentOption) {
  163. return variable.setValue(currentOption);
  164. } else {
  165. if (!variable.options.length) {
  166. return Promise.resolve();
  167. }
  168. return variable.setValue(variable.options[0]);
  169. }
  170. }
  171. }
  172. setOptionFromUrl(variable, urlValue) {
  173. let promise = this.$q.when();
  174. if (variable.refresh) {
  175. promise = variable.updateOptions();
  176. }
  177. return promise.then(() => {
  178. let option = _.find(variable.options, op => {
  179. return op.text === urlValue || op.value === urlValue;
  180. });
  181. let defaultText = urlValue;
  182. const defaultValue = urlValue;
  183. if (!option && _.isArray(urlValue)) {
  184. defaultText = [];
  185. for (let n = 0; n < urlValue.length; n++) {
  186. const t = _.find(variable.options, op => {
  187. return op.value === urlValue[n];
  188. });
  189. if (t) {
  190. defaultText.push(t.text);
  191. }
  192. }
  193. }
  194. option = option || { text: defaultText, value: defaultValue };
  195. return variable.setValue(option);
  196. });
  197. }
  198. setOptionAsCurrent(variable, option) {
  199. variable.current = _.cloneDeep(option);
  200. if (_.isArray(variable.current.text)) {
  201. variable.current.text = variable.current.text.join(' + ');
  202. }
  203. this.selectOptionsForCurrentValue(variable);
  204. return this.variableUpdated(variable);
  205. }
  206. updateUrlParamsWithCurrentVariables() {
  207. // update url
  208. const params = this.$location.search();
  209. // remove variable params
  210. _.each(params, (value, key) => {
  211. if (key.indexOf('var-') === 0) {
  212. delete params[key];
  213. }
  214. });
  215. // add new values
  216. this.templateSrv.fillVariableValuesForUrl(params);
  217. // update url
  218. this.$location.search(params);
  219. }
  220. setAdhocFilter(options) {
  221. let variable = _.find(this.variables, {
  222. type: 'adhoc',
  223. datasource: options.datasource,
  224. });
  225. if (!variable) {
  226. variable = this.createVariableFromModel({
  227. name: 'Filters',
  228. type: 'adhoc',
  229. datasource: options.datasource,
  230. });
  231. this.addVariable(variable);
  232. }
  233. const filters = variable.filters;
  234. let filter = _.find(filters, { key: options.key, value: options.value });
  235. if (!filter) {
  236. filter = { key: options.key, value: options.value };
  237. filters.push(filter);
  238. }
  239. filter.operator = options.operator;
  240. this.variableUpdated(variable, true);
  241. }
  242. createGraph() {
  243. const g = new Graph();
  244. this.variables.forEach(v1 => {
  245. g.createNode(v1.name);
  246. this.variables.forEach(v2 => {
  247. if (v1 === v2) {
  248. return;
  249. }
  250. if (v1.dependsOn(v2)) {
  251. g.link(v1.name, v2.name);
  252. }
  253. });
  254. });
  255. return g;
  256. }
  257. }
  258. coreModule.service('variableSrv', VariableSrv);