grafana/public/app/features/templating/template_srv.ts

363 lines
9.5 KiB
TypeScript
Raw Normal View History

2017-12-20 05:33:33 -06:00
import kbn from 'app/core/utils/kbn';
import _ from 'lodash';
import { variableRegex } from 'app/features/templating/variable';
import { escapeHtml } from 'app/core/utils/text';
import { ScopedVars, TimeRange } from '@grafana/data';
function luceneEscape(value: string) {
return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1');
}
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
interface FieldAccessorCache {
[key: string]: (obj: any) => any;
}
export class TemplateSrv {
variables: any[];
private regex = variableRegex;
private index: any = {};
private grafanaVariables: any = {};
private builtIns: any = {};
2019-01-29 08:05:28 -06:00
private timeRange: TimeRange = null;
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
private fieldAccessorCache: FieldAccessorCache = {};
constructor() {
2017-12-20 05:33:33 -06:00
this.builtIns['__interval'] = { text: '1s', value: '1s' };
this.builtIns['__interval_ms'] = { text: '100', value: '100' };
this.variables = [];
}
init(variables: any, timeRange?: TimeRange) {
this.variables = variables;
2019-01-29 08:05:28 -06:00
this.timeRange = timeRange;
this.updateIndex();
}
getBuiltInIntervalValue() {
return this.builtIns.__interval.value;
}
updateIndex() {
const existsOrEmpty = (value: any) => value || value === '';
this.index = this.variables.reduce((acc, currentValue) => {
if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) {
acc[currentValue.name] = currentValue;
}
return acc;
}, {});
2019-01-29 08:05:28 -06:00
if (this.timeRange) {
const from = this.timeRange.from.valueOf().toString();
const to = this.timeRange.to.valueOf().toString();
this.index = {
...this.index,
['__from']: {
current: { value: from, text: from },
},
['__to']: {
current: { value: to, text: to },
},
};
}
}
updateTimeRange(timeRange: TimeRange) {
2019-01-29 08:05:28 -06:00
this.timeRange = timeRange;
this.updateIndex();
}
variableInitialized(variable: any) {
this.index[variable.name] = variable;
}
getAdhocFilters(datasourceName: string) {
let filters: any = [];
if (this.variables) {
for (let i = 0; i < this.variables.length; i++) {
const variable = this.variables[i];
if (variable.type !== 'adhoc') {
continue;
}
// null is the "default" datasource
if (variable.datasource === null || variable.datasource === datasourceName) {
filters = filters.concat(variable.filters);
} else if (variable.datasource.indexOf('$') === 0) {
if (this.replace(variable.datasource) === datasourceName) {
filters = filters.concat(variable.filters);
}
}
}
}
return filters;
}
luceneFormat(value: any) {
2017-12-20 05:33:33 -06:00
if (typeof value === 'string') {
return luceneEscape(value);
}
if (value instanceof Array && value.length === 0) {
return '__empty__';
}
const quotedValues = _.map(value, val => {
return '"' + luceneEscape(val) + '"';
});
2017-12-20 05:33:33 -06:00
return '(' + quotedValues.join(' OR ') + ')';
}
// encode string according to RFC 3986; in contrast to encodeURIComponent()
// also the sub-delims "!", "'", "(", ")" and "*" are encoded;
// unicode handling uses UTF-8 as in ECMA-262.
encodeURIComponentStrict(str: string) {
2019-01-29 08:05:28 -06:00
return encodeURIComponent(str).replace(/[!'()*]/g, c => {
return (
'%' +
c
.charCodeAt(0)
.toString(16)
.toUpperCase()
);
});
}
formatValue(value: any, format: any, variable: any) {
// for some scopedVars there is no variable
variable = variable || {};
2017-12-20 05:33:33 -06:00
if (typeof format === 'function') {
return format(value, variable, this.formatValue);
}
switch (format) {
2017-12-20 05:33:33 -06:00
case 'regex': {
if (typeof value === 'string') {
return kbn.regexEscape(value);
}
const escapedValues = _.map(value, kbn.regexEscape);
2018-02-15 11:44:03 -06:00
if (escapedValues.length === 1) {
return escapedValues[0];
}
2017-12-20 05:33:33 -06:00
return '(' + escapedValues.join('|') + ')';
}
2017-12-20 05:33:33 -06:00
case 'lucene': {
return this.luceneFormat(value);
}
2017-12-20 05:33:33 -06:00
case 'pipe': {
if (typeof value === 'string') {
return value;
}
2017-12-20 05:33:33 -06:00
return value.join('|');
}
2017-12-20 05:33:33 -06:00
case 'distributed': {
if (typeof value === 'string') {
return value;
}
return this.distributeVariable(value, variable.name);
}
2018-03-07 06:35:54 -06:00
case 'csv': {
if (_.isArray(value)) {
return value.join(',');
}
return value;
}
case 'html': {
if (_.isArray(value)) {
return escapeHtml(value.join(', '));
}
return escapeHtml(value);
}
2019-02-06 23:07:41 -06:00
case 'json': {
return JSON.stringify(value);
}
case 'percentencode': {
2018-07-30 10:19:41 -05:00
// like glob, but url escaped
if (_.isArray(value)) {
return this.encodeURIComponentStrict('{' + value.join(',') + '}');
2018-07-30 10:19:41 -05:00
}
return this.encodeURIComponentStrict(value);
2018-07-30 10:19:41 -05:00
}
default: {
if (_.isArray(value) && value.length > 1) {
2017-12-20 05:33:33 -06:00
return '{' + value.join(',') + '}';
}
return value;
}
}
}
setGrafanaVariable(name: string, value: any) {
this.grafanaVariables[name] = value;
}
getVariableName(expression: string) {
this.regex.lastIndex = 0;
const match = this.regex.exec(expression);
if (!match) {
return null;
}
const variableName = match.slice(1).find(match => match !== undefined);
return variableName;
}
variableExists(expression: string) {
const name = this.getVariableName(expression);
return name && this.index[name] !== void 0;
}
highlightVariablesAsHtml(str: string) {
if (!str || !_.isString(str)) {
return str;
}
str = _.escape(str);
this.regex.lastIndex = 0;
2018-02-23 08:51:19 -06:00
return str.replace(this.regex, (match, var1, var2, fmt2, var3) => {
if (this.index[var1 || var2 || var3] || this.builtIns[var1 || var2 || var3]) {
2017-12-20 05:33:33 -06:00
return '<span class="template-variable">' + match + '</span>';
}
return match;
});
}
getAllValue(variable: any) {
if (variable.allValue) {
return variable.allValue;
}
const values = [];
for (let i = 1; i < variable.options.length; i++) {
values.push(variable.options[i].value);
}
return values;
}
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
getFieldAccessor(fieldPath: string) {
const accessor = this.fieldAccessorCache[fieldPath];
if (accessor) {
return accessor;
}
return (this.fieldAccessorCache[fieldPath] = _.property(fieldPath));
}
getVariableValue(variableName: string, fieldPath: string | undefined, scopedVars: ScopedVars) {
const scopedVar = scopedVars[variableName];
if (!scopedVar) {
return null;
}
if (fieldPath) {
return this.getFieldAccessor(fieldPath)(scopedVar.value);
}
return scopedVar.value;
}
replace(target: string, scopedVars?: ScopedVars, format?: string | Function): any {
if (!target) {
return target;
}
this.regex.lastIndex = 0;
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
return target.replace(this.regex, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
const variableName = var1 || var2 || var3;
const variable = this.index[variableName];
const fmt = fmt2 || fmt3 || format;
if (scopedVars) {
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
const value = this.getVariableValue(variableName, fieldPath, scopedVars);
if (value !== null && value !== undefined) {
return this.formatValue(value, fmt, variable);
}
}
if (!variable) {
return match;
}
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
const systemValue = this.grafanaVariables[variable.current.value];
if (systemValue) {
return this.formatValue(systemValue, fmt, variable);
}
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
let value = variable.current.value;
if (this.isAllValue(value)) {
value = this.getAllValue(variable);
2018-04-13 12:48:37 -05:00
// skip formatting of custom all values
if (variable.allValue) {
return this.replace(value);
}
}
const res = this.formatValue(value, fmt, variable);
return res;
});
}
isAllValue(value: any) {
return value === '$__all' || (Array.isArray(value) && value[0] === '$__all');
}
replaceWithText(target: string, scopedVars: ScopedVars) {
if (!target) {
return target;
}
let variable;
this.regex.lastIndex = 0;
return target.replace(this.regex, (match: any, var1: any, var2: any, fmt2: any, var3: any) => {
if (scopedVars) {
const option = scopedVars[var1 || var2 || var3];
if (option) {
return option.text;
}
}
2018-02-23 08:51:19 -06:00
variable = this.index[var1 || var2 || var3];
if (!variable) {
return match;
}
2019-01-23 22:57:11 -06:00
const value = this.grafanaVariables[variable.current.value];
2019-01-29 08:05:28 -06:00
return typeof value === 'string' ? value : variable.current.text;
});
}
fillVariableValuesForUrl(params: any, scopedVars?: ScopedVars) {
_.each(this.variables, variable => {
if (scopedVars && scopedVars[variable.name] !== void 0) {
if (scopedVars[variable.name].skipUrlSync) {
return;
}
2017-12-20 05:33:33 -06:00
params['var-' + variable.name] = scopedVars[variable.name].value;
} else {
if (variable.skipUrlSync) {
return;
}
2017-12-20 05:33:33 -06:00
params['var-' + variable.name] = variable.getValueForUrl();
}
});
}
distributeVariable(value: any, variable: any) {
2019-04-15 05:11:52 -05:00
value = _.map(value, (val: any, index: number) => {
if (index !== 0) {
2017-12-20 05:33:33 -06:00
return variable + '=' + val;
} else {
return val;
}
});
2017-12-20 05:33:33 -06:00
return value.join(',');
}
}
export default new TemplateSrv();