variable_srv.ts 8.7 KB

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