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