variable_srv.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. /**
  186. * Sets the current selected option (or options) based on the query params in the url. It is possible for values
  187. * in the url to not match current options of the variable. In that case the variables current value will be still set
  188. * to that value.
  189. * @param variable Instance of Variable
  190. * @param urlValue Value of the query parameter
  191. */
  192. setOptionFromUrl(variable: any, urlValue: string | string[]): Promise<any> {
  193. let promise = this.$q.when();
  194. if (variable.refresh) {
  195. promise = variable.updateOptions();
  196. }
  197. return promise.then(() => {
  198. // Simple case. Value in url matches existing options text or value.
  199. let option: any = _.find(variable.options, op => {
  200. return op.text === urlValue || op.value === urlValue;
  201. });
  202. // No luck either it is array or value does not exist in the variables options.
  203. if (!option) {
  204. let defaultText = urlValue;
  205. const defaultValue = urlValue;
  206. if (_.isArray(urlValue)) {
  207. // Multiple values in the url. We construct text as a list of texts from all matched options.
  208. defaultText = urlValue.reduce((acc, item) => {
  209. const t: any = _.find(variable.options, { value: item });
  210. if (t) {
  211. acc.push(t.text);
  212. } else {
  213. acc.push(item);
  214. }
  215. return acc;
  216. }, []);
  217. }
  218. // It is possible that we did not match the value to any existing option. In that case the url value will be
  219. // used anyway for both text and value.
  220. option = { text: defaultText, value: defaultValue };
  221. }
  222. if (variable.multi) {
  223. // In case variable is multiple choice, we cast to array to preserve the same behaviour as when selecting
  224. // the option directly, which will return even single value in an array.
  225. option = { ...option, value: _.castArray(option.value) };
  226. }
  227. return variable.setValue(option);
  228. });
  229. }
  230. setOptionAsCurrent(variable, option) {
  231. variable.current = _.cloneDeep(option);
  232. if (_.isArray(variable.current.text) && variable.current.text.length > 0) {
  233. variable.current.text = variable.current.text.join(' + ');
  234. } else if (_.isArray(variable.current.value) && variable.current.value[0] !== '$__all') {
  235. variable.current.text = variable.current.value.join(' + ');
  236. }
  237. this.selectOptionsForCurrentValue(variable);
  238. return this.variableUpdated(variable);
  239. }
  240. updateUrlParamsWithCurrentVariables() {
  241. // update url
  242. const params = this.$location.search();
  243. // remove variable params
  244. _.each(params, (value, key) => {
  245. if (key.indexOf('var-') === 0) {
  246. delete params[key];
  247. }
  248. });
  249. // add new values
  250. this.templateSrv.fillVariableValuesForUrl(params);
  251. // update url
  252. this.$location.search(params);
  253. }
  254. setAdhocFilter(options) {
  255. let variable: any = _.find(this.variables, {
  256. type: 'adhoc',
  257. datasource: options.datasource,
  258. } as any);
  259. if (!variable) {
  260. variable = this.createVariableFromModel({
  261. name: 'Filters',
  262. type: 'adhoc',
  263. datasource: options.datasource,
  264. });
  265. this.addVariable(variable);
  266. }
  267. const filters = variable.filters;
  268. let filter: any = _.find(filters, { key: options.key, value: options.value });
  269. if (!filter) {
  270. filter = { key: options.key, value: options.value };
  271. filters.push(filter);
  272. }
  273. filter.operator = options.operator;
  274. this.variableUpdated(variable, true);
  275. }
  276. createGraph() {
  277. const g = new Graph();
  278. this.variables.forEach(v => {
  279. g.createNode(v.name);
  280. });
  281. this.variables.forEach(v1 => {
  282. this.variables.forEach(v2 => {
  283. if (v1 === v2) {
  284. return;
  285. }
  286. if (v1.dependsOn(v2)) {
  287. g.link(v1.name, v2.name);
  288. }
  289. });
  290. });
  291. return g;
  292. }
  293. }
  294. coreModule.service('variableSrv', VariableSrv);