From 026bf1f9cac2e29fe120d23a35881b14a6e84ec0 Mon Sep 17 00:00:00 2001 From: Kyle Brandt Date: Thu, 18 Mar 2021 08:02:37 -0400 Subject: [PATCH] SSE/InfluxDB: Change InfluxQL to work with server side expressions (#31691) * SSE/InfluxDB: Change InfluxQL to work with server side expressions updates the request to handle EpochMS as the time range (which is what expressions sends) and the response to use millisecond timestamps instead of seconds. fixes #31604 similar to https://github.com/grafana/grafana/pull/31455 --- pkg/tsdb/influxdb/query.go | 36 ++++++++++++++++++++++++++++ pkg/tsdb/influxdb/response_parser.go | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/pkg/tsdb/influxdb/query.go b/pkg/tsdb/influxdb/query.go index cceba318c8c..763fa009f5d 100644 --- a/pkg/tsdb/influxdb/query.go +++ b/pkg/tsdb/influxdb/query.go @@ -78,7 +78,29 @@ func (query *Query) renderTags() []string { return res } +func isTimeRangeNumeric(tr *plugins.DataTimeRange) bool { + if _, err := strconv.ParseInt(tr.From, 10, 64); err != nil { + return false + } + if _, err := strconv.ParseInt(tr.To, 10, 64); err != nil { + return false + } + return true +} + func (query *Query) renderTimeFilter(queryContext plugins.DataQuery) string { + // If from expressions + if isTimeRangeNumeric(queryContext.TimeRange) { + from, to, err := epochMStoInfluxTime(queryContext.TimeRange) + if err == nil { + return fmt.Sprintf(" time > %s and time < %s ", from, to) + } + + // on error fallback to original time range processing. + glog.Warn("failed to parse expected time range in query, falling back to non-expression time range processing", "error", err) + } + + // else from dashboard alerting from := "now() - " + queryContext.TimeRange.From to := "" @@ -162,3 +184,17 @@ func (query *Query) renderTz() string { } return fmt.Sprintf(" tz('%s')", tz) } + +func epochMStoInfluxTime(tr *plugins.DataTimeRange) (string, string, error) { + from, err := strconv.ParseInt(tr.From, 10, 64) + if err != nil { + return "", "", err + } + + to, err := strconv.ParseInt(tr.To, 10, 64) + if err != nil { + return "", "", err + } + + return fmt.Sprintf("%dms", from), fmt.Sprintf("%dms", to), nil +} diff --git a/pkg/tsdb/influxdb/response_parser.go b/pkg/tsdb/influxdb/response_parser.go index ccdf1117c3a..db837a0de5d 100644 --- a/pkg/tsdb/influxdb/response_parser.go +++ b/pkg/tsdb/influxdb/response_parser.go @@ -127,7 +127,7 @@ func (rp *ResponseParser) parseTimepoint(valuePair []interface{}, valuePosition return plugins.DataTimePoint{}, err } - return plugins.DataTimePoint{value, null.FloatFrom(timestamp)}, nil + return plugins.DataTimePoint{value, null.FloatFrom(timestamp * 1000)}, nil } func (rp *ResponseParser) parseValue(value interface{}) null.Float {