template_srv.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import kbn from 'app/core/utils/kbn';
  2. import _ from 'lodash';
  3. import { variableRegex } from 'app/features/templating/variable';
  4. import { ScopedVars } from '@grafana/ui';
  5. import { TimeRange } from '@grafana/data';
  6. function luceneEscape(value: string) {
  7. return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1');
  8. }
  9. export class TemplateSrv {
  10. variables: any[];
  11. private regex = variableRegex;
  12. private index: any = {};
  13. private grafanaVariables: any = {};
  14. private builtIns: any = {};
  15. private timeRange: TimeRange = null;
  16. constructor() {
  17. this.builtIns['__interval'] = { text: '1s', value: '1s' };
  18. this.builtIns['__interval_ms'] = { text: '100', value: '100' };
  19. this.variables = [];
  20. }
  21. init(variables: any, timeRange?: TimeRange) {
  22. this.variables = variables;
  23. this.timeRange = timeRange;
  24. this.updateIndex();
  25. }
  26. getBuiltInIntervalValue() {
  27. return this.builtIns.__interval.value;
  28. }
  29. updateIndex() {
  30. const existsOrEmpty = (value: any) => value || value === '';
  31. this.index = this.variables.reduce((acc, currentValue) => {
  32. if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) {
  33. acc[currentValue.name] = currentValue;
  34. }
  35. return acc;
  36. }, {});
  37. if (this.timeRange) {
  38. const from = this.timeRange.from.valueOf().toString();
  39. const to = this.timeRange.to.valueOf().toString();
  40. this.index = {
  41. ...this.index,
  42. ['__from']: {
  43. current: { value: from, text: from },
  44. },
  45. ['__to']: {
  46. current: { value: to, text: to },
  47. },
  48. };
  49. }
  50. }
  51. updateTimeRange(timeRange: TimeRange) {
  52. this.timeRange = timeRange;
  53. this.updateIndex();
  54. }
  55. variableInitialized(variable: any) {
  56. this.index[variable.name] = variable;
  57. }
  58. getAdhocFilters(datasourceName: string) {
  59. let filters: any = [];
  60. if (this.variables) {
  61. for (let i = 0; i < this.variables.length; i++) {
  62. const variable = this.variables[i];
  63. if (variable.type !== 'adhoc') {
  64. continue;
  65. }
  66. // null is the "default" datasource
  67. if (variable.datasource === null || variable.datasource === datasourceName) {
  68. filters = filters.concat(variable.filters);
  69. } else if (variable.datasource.indexOf('$') === 0) {
  70. if (this.replace(variable.datasource) === datasourceName) {
  71. filters = filters.concat(variable.filters);
  72. }
  73. }
  74. }
  75. }
  76. return filters;
  77. }
  78. luceneFormat(value: any) {
  79. if (typeof value === 'string') {
  80. return luceneEscape(value);
  81. }
  82. if (value instanceof Array && value.length === 0) {
  83. return '__empty__';
  84. }
  85. const quotedValues = _.map(value, val => {
  86. return '"' + luceneEscape(val) + '"';
  87. });
  88. return '(' + quotedValues.join(' OR ') + ')';
  89. }
  90. // encode string according to RFC 3986; in contrast to encodeURIComponent()
  91. // also the sub-delims "!", "'", "(", ")" and "*" are encoded;
  92. // unicode handling uses UTF-8 as in ECMA-262.
  93. encodeURIComponentStrict(str: string) {
  94. return encodeURIComponent(str).replace(/[!'()*]/g, c => {
  95. return (
  96. '%' +
  97. c
  98. .charCodeAt(0)
  99. .toString(16)
  100. .toUpperCase()
  101. );
  102. });
  103. }
  104. formatValue(value: any, format: any, variable: any) {
  105. // for some scopedVars there is no variable
  106. variable = variable || {};
  107. if (typeof format === 'function') {
  108. return format(value, variable, this.formatValue);
  109. }
  110. switch (format) {
  111. case 'regex': {
  112. if (typeof value === 'string') {
  113. return kbn.regexEscape(value);
  114. }
  115. const escapedValues = _.map(value, kbn.regexEscape);
  116. if (escapedValues.length === 1) {
  117. return escapedValues[0];
  118. }
  119. return '(' + escapedValues.join('|') + ')';
  120. }
  121. case 'lucene': {
  122. return this.luceneFormat(value);
  123. }
  124. case 'pipe': {
  125. if (typeof value === 'string') {
  126. return value;
  127. }
  128. return value.join('|');
  129. }
  130. case 'distributed': {
  131. if (typeof value === 'string') {
  132. return value;
  133. }
  134. return this.distributeVariable(value, variable.name);
  135. }
  136. case 'csv': {
  137. if (_.isArray(value)) {
  138. return value.join(',');
  139. }
  140. return value;
  141. }
  142. case 'json': {
  143. return JSON.stringify(value);
  144. }
  145. case 'percentencode': {
  146. // like glob, but url escaped
  147. if (_.isArray(value)) {
  148. return this.encodeURIComponentStrict('{' + value.join(',') + '}');
  149. }
  150. return this.encodeURIComponentStrict(value);
  151. }
  152. default: {
  153. if (_.isArray(value)) {
  154. return '{' + value.join(',') + '}';
  155. }
  156. return value;
  157. }
  158. }
  159. }
  160. setGrafanaVariable(name: string, value: any) {
  161. this.grafanaVariables[name] = value;
  162. }
  163. getVariableName(expression: string) {
  164. this.regex.lastIndex = 0;
  165. const match = this.regex.exec(expression);
  166. if (!match) {
  167. return null;
  168. }
  169. const variableName = match.slice(1).find(match => match !== undefined);
  170. return variableName;
  171. }
  172. variableExists(expression: string) {
  173. const name = this.getVariableName(expression);
  174. return name && this.index[name] !== void 0;
  175. }
  176. highlightVariablesAsHtml(str: string) {
  177. if (!str || !_.isString(str)) {
  178. return str;
  179. }
  180. str = _.escape(str);
  181. this.regex.lastIndex = 0;
  182. return str.replace(this.regex, (match, var1, var2, fmt2, var3) => {
  183. if (this.index[var1 || var2 || var3] || this.builtIns[var1 || var2 || var3]) {
  184. return '<span class="template-variable">' + match + '</span>';
  185. }
  186. return match;
  187. });
  188. }
  189. getAllValue(variable: any) {
  190. if (variable.allValue) {
  191. return variable.allValue;
  192. }
  193. const values = [];
  194. for (let i = 1; i < variable.options.length; i++) {
  195. values.push(variable.options[i].value);
  196. }
  197. return values;
  198. }
  199. replace(target: string, scopedVars?: ScopedVars, format?: string | Function): any {
  200. if (!target) {
  201. return target;
  202. }
  203. let variable, systemValue, value, fmt;
  204. this.regex.lastIndex = 0;
  205. return target.replace(this.regex, (match, var1, var2, fmt2, var3, fmt3) => {
  206. variable = this.index[var1 || var2 || var3];
  207. fmt = fmt2 || fmt3 || format;
  208. if (scopedVars) {
  209. value = scopedVars[var1 || var2 || var3];
  210. if (value) {
  211. return this.formatValue(value.value, fmt, variable);
  212. }
  213. }
  214. if (!variable) {
  215. return match;
  216. }
  217. systemValue = this.grafanaVariables[variable.current.value];
  218. if (systemValue) {
  219. return this.formatValue(systemValue, fmt, variable);
  220. }
  221. value = variable.current.value;
  222. if (this.isAllValue(value)) {
  223. value = this.getAllValue(variable);
  224. // skip formatting of custom all values
  225. if (variable.allValue) {
  226. return this.replace(value);
  227. }
  228. }
  229. const res = this.formatValue(value, fmt, variable);
  230. return res;
  231. });
  232. }
  233. isAllValue(value: any) {
  234. return value === '$__all' || (Array.isArray(value) && value[0] === '$__all');
  235. }
  236. replaceWithText(target: string, scopedVars: ScopedVars) {
  237. if (!target) {
  238. return target;
  239. }
  240. let variable;
  241. this.regex.lastIndex = 0;
  242. return target.replace(this.regex, (match: any, var1: any, var2: any, fmt2: any, var3: any) => {
  243. if (scopedVars) {
  244. const option = scopedVars[var1 || var2 || var3];
  245. if (option) {
  246. return option.text;
  247. }
  248. }
  249. variable = this.index[var1 || var2 || var3];
  250. if (!variable) {
  251. return match;
  252. }
  253. const value = this.grafanaVariables[variable.current.value];
  254. return typeof value === 'string' ? value : variable.current.text;
  255. });
  256. }
  257. fillVariableValuesForUrl(params: any, scopedVars?: ScopedVars) {
  258. _.each(this.variables, variable => {
  259. if (scopedVars && scopedVars[variable.name] !== void 0) {
  260. if (scopedVars[variable.name].skipUrlSync) {
  261. return;
  262. }
  263. params['var-' + variable.name] = scopedVars[variable.name].value;
  264. } else {
  265. if (variable.skipUrlSync) {
  266. return;
  267. }
  268. params['var-' + variable.name] = variable.getValueForUrl();
  269. }
  270. });
  271. }
  272. distributeVariable(value: any, variable: any) {
  273. value = _.map(value, (val: any, index: number) => {
  274. if (index !== 0) {
  275. return variable + '=' + val;
  276. } else {
  277. return val;
  278. }
  279. });
  280. return value.join(',');
  281. }
  282. }
  283. export default new TemplateSrv();