query_variable.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import _ from 'lodash';
  2. import { Variable, containsVariable, assignModelProperties, variableTypes } from './variable';
  3. import { stringToJsRegex } from '@grafana/data';
  4. import DatasourceSrv from '../plugins/datasource_srv';
  5. import { TemplateSrv } from './template_srv';
  6. import { VariableSrv } from './variable_srv';
  7. import { TimeSrv } from '../dashboard/services/TimeSrv';
  8. function getNoneOption() {
  9. return { text: 'None', value: '', isNone: true };
  10. }
  11. export class QueryVariable implements Variable {
  12. datasource: any;
  13. query: any;
  14. regex: any;
  15. sort: any;
  16. options: any;
  17. current: any;
  18. refresh: number;
  19. hide: number;
  20. name: string;
  21. multi: boolean;
  22. includeAll: boolean;
  23. useTags: boolean;
  24. tagsQuery: string;
  25. tagValuesQuery: string;
  26. tags: any[];
  27. skipUrlSync: boolean;
  28. definition: string;
  29. defaults: any = {
  30. type: 'query',
  31. label: null,
  32. query: '',
  33. regex: '',
  34. sort: 0,
  35. datasource: null,
  36. refresh: 0,
  37. hide: 0,
  38. name: '',
  39. multi: false,
  40. includeAll: false,
  41. allValue: null,
  42. options: [],
  43. current: {},
  44. tags: [],
  45. useTags: false,
  46. tagsQuery: '',
  47. tagValuesQuery: '',
  48. skipUrlSync: false,
  49. definition: '',
  50. };
  51. /** @ngInject */
  52. constructor(
  53. private model: any,
  54. private datasourceSrv: DatasourceSrv,
  55. private templateSrv: TemplateSrv,
  56. private variableSrv: VariableSrv,
  57. private timeSrv: TimeSrv
  58. ) {
  59. // copy model properties to this instance
  60. assignModelProperties(this, model, this.defaults);
  61. }
  62. getSaveModel() {
  63. // copy back model properties to model
  64. assignModelProperties(this.model, this, this.defaults);
  65. // remove options
  66. if (this.refresh !== 0) {
  67. this.model.options = [];
  68. }
  69. return this.model;
  70. }
  71. setValue(option: any) {
  72. return this.variableSrv.setOptionAsCurrent(this, option);
  73. }
  74. setValueFromUrl(urlValue: any) {
  75. return this.variableSrv.setOptionFromUrl(this, urlValue);
  76. }
  77. getValueForUrl() {
  78. if (this.current.text === 'All') {
  79. return 'All';
  80. }
  81. return this.current.value;
  82. }
  83. updateOptions() {
  84. return this.datasourceSrv
  85. .get(this.datasource)
  86. .then(this.updateOptionsFromMetricFindQuery.bind(this))
  87. .then(this.updateTags.bind(this))
  88. .then(this.variableSrv.validateVariableSelectionState.bind(this.variableSrv, this));
  89. }
  90. updateTags(datasource: any) {
  91. if (this.useTags) {
  92. return this.metricFindQuery(datasource, this.tagsQuery).then((results: any[]) => {
  93. this.tags = [];
  94. for (let i = 0; i < results.length; i++) {
  95. this.tags.push(results[i].text);
  96. }
  97. return datasource;
  98. });
  99. } else {
  100. delete this.tags;
  101. }
  102. return datasource;
  103. }
  104. getValuesForTag(tagKey: string) {
  105. return this.datasourceSrv.get(this.datasource).then(datasource => {
  106. const query = this.tagValuesQuery.replace('$tag', tagKey);
  107. return this.metricFindQuery(datasource, query).then((results: any) => {
  108. return _.map(results, value => {
  109. return value.text;
  110. });
  111. });
  112. });
  113. }
  114. updateOptionsFromMetricFindQuery(datasource: any) {
  115. return this.metricFindQuery(datasource, this.query).then((results: any) => {
  116. this.options = this.metricNamesToVariableValues(results);
  117. if (this.includeAll) {
  118. this.addAllOption();
  119. }
  120. if (!this.options.length) {
  121. this.options.push(getNoneOption());
  122. }
  123. return datasource;
  124. });
  125. }
  126. metricFindQuery(datasource: any, query: string) {
  127. const options: any = { range: undefined, variable: this };
  128. if (this.refresh === 2) {
  129. options.range = this.timeSrv.timeRange();
  130. }
  131. return datasource.metricFindQuery(query, options);
  132. }
  133. addAllOption() {
  134. this.options.unshift({ text: 'All', value: '$__all' });
  135. }
  136. metricNamesToVariableValues(metricNames: any[]) {
  137. let regex, options, i, matches;
  138. options = [];
  139. if (this.regex) {
  140. regex = stringToJsRegex(this.templateSrv.replace(this.regex, {}, 'regex'));
  141. }
  142. for (i = 0; i < metricNames.length; i++) {
  143. const item = metricNames[i];
  144. let text = item.text === undefined || item.text === null ? item.value : item.text;
  145. let value = item.value === undefined || item.value === null ? item.text : item.value;
  146. if (_.isNumber(value)) {
  147. value = value.toString();
  148. }
  149. if (_.isNumber(text)) {
  150. text = text.toString();
  151. }
  152. if (regex) {
  153. matches = regex.exec(value);
  154. if (!matches) {
  155. continue;
  156. }
  157. if (matches.length > 1) {
  158. value = matches[1];
  159. text = matches[1];
  160. }
  161. }
  162. options.push({ text: text, value: value });
  163. }
  164. options = _.uniqBy(options, 'value');
  165. return this.sortVariableValues(options, this.sort);
  166. }
  167. sortVariableValues(options: any[], sortOrder: number) {
  168. if (sortOrder === 0) {
  169. return options;
  170. }
  171. const sortType = Math.ceil(sortOrder / 2);
  172. const reverseSort = sortOrder % 2 === 0;
  173. if (sortType === 1) {
  174. options = _.sortBy(options, 'text');
  175. } else if (sortType === 2) {
  176. options = _.sortBy(options, opt => {
  177. const matches = opt.text.match(/.*?(\d+).*/);
  178. if (!matches || matches.length < 2) {
  179. return -1;
  180. } else {
  181. return parseInt(matches[1], 10);
  182. }
  183. });
  184. } else if (sortType === 3) {
  185. options = _.sortBy(options, opt => {
  186. return _.toLower(opt.text);
  187. });
  188. }
  189. if (reverseSort) {
  190. options = options.reverse();
  191. }
  192. return options;
  193. }
  194. dependsOn(variable: any) {
  195. return containsVariable(this.query, this.datasource, this.regex, variable.name);
  196. }
  197. }
  198. // @ts-ignore
  199. variableTypes['query'] = {
  200. name: 'Query',
  201. ctor: QueryVariable,
  202. description: 'Variable values are fetched from a datasource query',
  203. supportsMulti: true,
  204. };