variable_srv.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // Libaries
  2. import angular, { IQService, ILocationService, auto, IPromise } 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/data';
  13. export class VariableSrv {
  14. dashboard: DashboardModel;
  15. variables: any[];
  16. /** @ngInject */
  17. constructor(
  18. private $q: IQService,
  19. private $location: ILocationService,
  20. private $injector: auto.IInjectorService,
  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: any, queryParams: any) {
  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: any) {
  87. // @ts-ignore
  88. const ctor = variableTypes[model.type].ctor;
  89. if (!ctor) {
  90. throw {
  91. message: 'Unable to find variable constructor for ' + model.type,
  92. };
  93. }
  94. const variable = this.$injector.instantiate(ctor, { model: model });
  95. return variable;
  96. }
  97. addVariable(variable: any) {
  98. this.variables.push(variable);
  99. this.templateSrv.updateIndex();
  100. this.dashboard.updateSubmenuVisibility();
  101. }
  102. removeVariable(variable: any) {
  103. const index = _.indexOf(this.variables, variable);
  104. this.variables.splice(index, 1);
  105. this.templateSrv.updateIndex();
  106. this.dashboard.updateSubmenuVisibility();
  107. }
  108. updateOptions(variable: any) {
  109. return variable.updateOptions();
  110. }
  111. variableUpdated(variable: any, emitChangeEvents?: any) {
  112. // if there is a variable lock ignore cascading update because we are in a boot up scenario
  113. if (variable.initLock) {
  114. return this.$q.when();
  115. }
  116. const g = this.createGraph();
  117. const node = g.getNode(variable.name);
  118. let promises = [];
  119. if (node) {
  120. promises = node.getOptimizedInputEdges().map(e => {
  121. return this.updateOptions(this.variables.find(v => v.name === e.inputNode.name));
  122. });
  123. }
  124. return this.$q.all(promises).then(() => {
  125. if (emitChangeEvents) {
  126. this.dashboard.templateVariableValueUpdated();
  127. this.dashboard.startRefresh();
  128. }
  129. });
  130. }
  131. selectOptionsForCurrentValue(variable: any) {
  132. let i, y, value, option;
  133. const selected: any = [];
  134. for (i = 0; i < variable.options.length; i++) {
  135. option = variable.options[i];
  136. option.selected = false;
  137. if (_.isArray(variable.current.value)) {
  138. for (y = 0; y < variable.current.value.length; y++) {
  139. value = variable.current.value[y];
  140. if (option.value === value) {
  141. option.selected = true;
  142. selected.push(option);
  143. }
  144. }
  145. } else if (option.value === variable.current.value) {
  146. option.selected = true;
  147. selected.push(option);
  148. }
  149. }
  150. return selected;
  151. }
  152. validateVariableSelectionState(variable: any) {
  153. if (!variable.current) {
  154. variable.current = {};
  155. }
  156. if (_.isArray(variable.current.value)) {
  157. let selected = this.selectOptionsForCurrentValue(variable);
  158. // if none pick first
  159. if (selected.length === 0) {
  160. selected = variable.options[0];
  161. } else {
  162. selected = {
  163. value: _.map(selected, val => {
  164. return val.value;
  165. }),
  166. text: _.map(selected, val => {
  167. return val.text;
  168. }),
  169. };
  170. }
  171. return variable.setValue(selected);
  172. } else {
  173. const currentOption: any = _.find(variable.options, {
  174. text: variable.current.text,
  175. });
  176. if (currentOption) {
  177. return variable.setValue(currentOption);
  178. } else {
  179. if (!variable.options.length) {
  180. return Promise.resolve();
  181. }
  182. return variable.setValue(variable.options[0]);
  183. }
  184. }
  185. }
  186. /**
  187. * Sets the current selected option (or options) based on the query params in the url. It is possible for values
  188. * in the url to not match current options of the variable. In that case the variables current value will be still set
  189. * to that value.
  190. * @param variable Instance of Variable
  191. * @param urlValue Value of the query parameter
  192. */
  193. setOptionFromUrl(variable: any, urlValue: string | string[]): IPromise<any> {
  194. let promise = this.$q.when();
  195. if (variable.refresh) {
  196. promise = variable.updateOptions();
  197. }
  198. return promise.then(() => {
  199. // Simple case. Value in url matches existing options text or value.
  200. let option: any = _.find(variable.options, op => {
  201. return op.text === urlValue || op.value === urlValue;
  202. });
  203. // No luck either it is array or value does not exist in the variables options.
  204. if (!option) {
  205. let defaultText = urlValue;
  206. const defaultValue = urlValue;
  207. if (_.isArray(urlValue)) {
  208. // Multiple values in the url. We construct text as a list of texts from all matched options.
  209. defaultText = urlValue.reduce((acc, item) => {
  210. const t: any = _.find(variable.options, { value: item });
  211. if (t) {
  212. acc.push(t.text);
  213. } else {
  214. acc.push(item);
  215. }
  216. return acc;
  217. }, []);
  218. }
  219. // It is possible that we did not match the value to any existing option. In that case the url value will be
  220. // used anyway for both text and value.
  221. option = { text: defaultText, value: defaultValue };
  222. }
  223. if (variable.multi) {
  224. // In case variable is multiple choice, we cast to array to preserve the same behaviour as when selecting
  225. // the option directly, which will return even single value in an array.
  226. option = { text: _.castArray(option.text), value: _.castArray(option.value) };
  227. }
  228. return variable.setValue(option);
  229. });
  230. }
  231. setOptionAsCurrent(variable: any, option: any) {
  232. variable.current = _.cloneDeep(option);
  233. if (_.isArray(variable.current.text) && variable.current.text.length > 0) {
  234. variable.current.text = variable.current.text.join(' + ');
  235. } else if (_.isArray(variable.current.value) && variable.current.value[0] !== '$__all') {
  236. variable.current.text = variable.current.value.join(' + ');
  237. }
  238. this.selectOptionsForCurrentValue(variable);
  239. return this.variableUpdated(variable);
  240. }
  241. updateUrlParamsWithCurrentVariables() {
  242. // update url
  243. const params = this.$location.search();
  244. // remove variable params
  245. _.each(params, (value, key) => {
  246. if (key.indexOf('var-') === 0) {
  247. delete params[key];
  248. }
  249. });
  250. // add new values
  251. this.templateSrv.fillVariableValuesForUrl(params);
  252. // update url
  253. this.$location.search(params);
  254. }
  255. setAdhocFilter(options: any) {
  256. let variable: any = _.find(this.variables, {
  257. type: 'adhoc',
  258. datasource: options.datasource,
  259. } as any);
  260. if (!variable) {
  261. variable = this.createVariableFromModel({
  262. name: 'Filters',
  263. type: 'adhoc',
  264. datasource: options.datasource,
  265. });
  266. this.addVariable(variable);
  267. }
  268. const filters = variable.filters;
  269. let filter: any = _.find(filters, { key: options.key, value: options.value });
  270. if (!filter) {
  271. filter = { key: options.key, value: options.value };
  272. filters.push(filter);
  273. }
  274. filter.operator = options.operator;
  275. this.variableUpdated(variable, true);
  276. }
  277. createGraph() {
  278. const g = new Graph();
  279. this.variables.forEach(v => {
  280. g.createNode(v.name);
  281. });
  282. this.variables.forEach(v1 => {
  283. this.variables.forEach(v2 => {
  284. if (v1 === v2) {
  285. return;
  286. }
  287. if (v1.dependsOn(v2)) {
  288. g.link(v1.name, v2.name);
  289. }
  290. });
  291. });
  292. return g;
  293. }
  294. }
  295. coreModule.service('variableSrv', VariableSrv);