variable_srv.ts 8.7 KB

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