Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add replace value #69

Merged
merged 1 commit into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkg/plugin/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"path"
"strconv"
"time"

"github.com/VictoriaMetrics/victorialogs-datasource/pkg/utils"
)

const (
Expand All @@ -20,6 +22,7 @@ type Query struct {
LegendFormat string `json:"legendFormat"`
MaxLines int `json:"maxLines"`
TimeRange TimeRange
IntervalMs int `json:"intervalMs"`
url *url.URL
}

Expand Down Expand Up @@ -72,6 +75,7 @@ func (q *Query) queryInstantURL(queryParams url.Values) string {
q.TimeRange.To = now
}

q.Expr = utils.ReplaceTemplateVariable(q.Expr, q.IntervalMs)
values.Set("query", q.Expr)
values.Set("limit", strconv.Itoa(q.MaxLines))
values.Set("start", strconv.FormatInt(q.TimeRange.From.Unix(), 10))
Expand Down
35 changes: 35 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ import (
"github.com/VictoriaMetrics/metricsql"
)

const (
varInterval = "$__interval"
)

var (
defaultResolution int64 = 1500
year = time.Hour * 24 * 365
day = time.Hour * 24
)

const (
// These values prevent from overflow when storing msec-precision time in int64.
minTimeMsecs = 0 // use 0 instead of `int64(-1<<63) / 1e6` because the storage engine doesn't actually support negative time
Expand Down Expand Up @@ -172,3 +182,28 @@ func ParseDuration(s string) (time.Duration, error) {
}
return time.Duration(ms) * time.Millisecond, nil
}

// ReplaceTemplateVariable get query and use it expression to remove grafana template variables with
func ReplaceTemplateVariable(expr string, interval int) string {
expr = strings.ReplaceAll(expr, varInterval, formatDuration(time.Duration(interval)*time.Millisecond))
return expr
}

func formatDuration(inter time.Duration) string {
switch {
case inter >= year:
return fmt.Sprintf("%dy", inter/year)
case inter >= day:
return fmt.Sprintf("%dd", inter/day)
case inter >= time.Hour:
return fmt.Sprintf("%dh", inter/time.Hour)
case inter >= time.Minute:
return fmt.Sprintf("%dm", inter/time.Minute)
case inter >= time.Second:
return fmt.Sprintf("%ds", inter/time.Second)
case inter >= time.Millisecond:
return fmt.Sprintf("%dms", inter/time.Millisecond)
default:
return "1ms"
}
}
Loading