datasource_variable.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { Variable, containsVariable, assignModelProperties, variableTypes } from './variable';
  2. import { stringToJsRegex } from '@grafana/ui';
  3. export class DatasourceVariable implements Variable {
  4. regex: any;
  5. query: string;
  6. options: any;
  7. current: any;
  8. multi: boolean;
  9. includeAll: boolean;
  10. refresh: any;
  11. skipUrlSync: boolean;
  12. defaults = {
  13. type: 'datasource',
  14. name: '',
  15. hide: 0,
  16. label: '',
  17. current: {},
  18. regex: '',
  19. options: [],
  20. query: '',
  21. multi: false,
  22. includeAll: false,
  23. refresh: 1,
  24. skipUrlSync: false,
  25. };
  26. /** @ngInject */
  27. constructor(private model, private datasourceSrv, private variableSrv, private templateSrv) {
  28. assignModelProperties(this, model, this.defaults);
  29. this.refresh = 1;
  30. }
  31. getSaveModel() {
  32. assignModelProperties(this.model, this, this.defaults);
  33. // don't persist options
  34. this.model.options = [];
  35. return this.model;
  36. }
  37. setValue(option) {
  38. return this.variableSrv.setOptionAsCurrent(this, option);
  39. }
  40. updateOptions() {
  41. const options = [];
  42. const sources = this.datasourceSrv.getMetricSources({ skipVariables: true });
  43. let regex;
  44. if (this.regex) {
  45. regex = this.templateSrv.replace(this.regex, null, 'regex');
  46. regex = stringToJsRegex(regex);
  47. }
  48. for (let i = 0; i < sources.length; i++) {
  49. const source = sources[i];
  50. // must match on type
  51. if (source.meta.id !== this.query) {
  52. continue;
  53. }
  54. if (regex && !regex.exec(source.name)) {
  55. continue;
  56. }
  57. options.push({ text: source.name, value: source.name });
  58. }
  59. if (options.length === 0) {
  60. options.push({ text: 'No data sources found', value: '' });
  61. }
  62. this.options = options;
  63. if (this.includeAll) {
  64. this.addAllOption();
  65. }
  66. return this.variableSrv.validateVariableSelectionState(this);
  67. }
  68. addAllOption() {
  69. this.options.unshift({ text: 'All', value: '$__all' });
  70. }
  71. dependsOn(variable) {
  72. if (this.regex) {
  73. return containsVariable(this.regex, variable.name);
  74. }
  75. return false;
  76. }
  77. setValueFromUrl(urlValue) {
  78. return this.variableSrv.setOptionFromUrl(this, urlValue);
  79. }
  80. getValueForUrl() {
  81. if (this.current.text === 'All') {
  82. return 'All';
  83. }
  84. return this.current.value;
  85. }
  86. }
  87. variableTypes['datasource'] = {
  88. name: 'Datasource',
  89. ctor: DatasourceVariable,
  90. supportsMulti: true,
  91. description: 'Enabled you to dynamically switch the datasource for multiple panels',
  92. };