2019-05-22 21:16:55 +00:00
package prometheus
import (
"flag"
"fmt"
"math"
"net/http"
"runtime"
2019-08-04 20:06:55 +00:00
"sort"
2019-05-22 21:16:55 +00:00
"strconv"
2019-08-04 20:06:55 +00:00
"sync"
2019-05-22 21:16:55 +00:00
"time"
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmselect/netstorage"
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmselect/promql"
2020-09-10 21:29:26 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmselect/searchutils"
2019-05-22 21:23:23 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/auth"
2020-05-14 19:01:51 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/fasttime"
2019-05-22 21:23:23 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/flagutil"
2020-07-31 15:00:21 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/httpserver"
2019-05-22 21:23:23 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
2019-05-22 21:16:55 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/storage"
"github.com/VictoriaMetrics/metrics"
2020-04-28 12:28:22 +00:00
"github.com/VictoriaMetrics/metricsql"
2020-03-10 19:45:15 +00:00
"github.com/valyala/fastjson/fastfloat"
2019-05-22 21:16:55 +00:00
"github.com/valyala/quicktemplate"
)
var (
2020-02-12 12:00:38 +00:00
latencyOffset = flag . Duration ( "search.latencyOffset" , time . Second * 30 , "The time when data points become visible in query results after the collection. " +
2019-10-28 10:30:50 +00:00
"Too small value can result in incomplete last points for query results" )
2020-09-10 21:29:26 +00:00
maxQueryLen = flagutil . NewBytes ( "search.maxQueryLen" , 16 * 1024 , "The maximum search query length in bytes" )
maxLookback = flag . Duration ( "search.maxLookback" , 0 , "Synonim to -search.lookback-delta from Prometheus. " +
2020-04-20 16:25:32 +00:00
"The value is dynamically detected from interval between time series datapoints if not set. It can be overridden on per-query basis via max_lookback arg. " +
"See also '-search.maxStalenessInterval' flag, which has the same meaining due to historical reasons" )
maxStalenessInterval = flag . Duration ( "search.maxStalenessInterval" , 0 , "The maximum interval for staleness calculations. " +
2020-04-20 16:41:59 +00:00
"By default it is automatically calculated from the median interval between samples. This flag could be useful for tuning " +
2020-04-20 16:25:32 +00:00
"Prometheus data model closer to Influx-style data model. See https://prometheus.io/docs/prometheus/latest/querying/basics/#staleness for details. " +
"See also '-search.maxLookback' flag, which has the same meanining due to historical reasons" )
2020-09-10 21:29:26 +00:00
selectNodes = flagutil . NewArray ( "selectNode" , "Addresses of vmselect nodes; usage: -selectNode=vmselect-host1:8481 -selectNode=vmselect-host2:8481" )
2019-05-22 21:16:55 +00:00
)
// Default step used if not set.
const defaultStep = 5 * 60 * 1000
// FederateHandler implements /federate . See https://prometheus.io/docs/prometheus/latest/federation/
2020-02-04 14:13:59 +00:00
func FederateHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2019-05-22 21:16:55 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse request form values: %w" , err )
2019-05-22 21:16:55 +00:00
}
matches := r . Form [ "match[]" ]
2019-06-20 11:05:07 +00:00
if len ( matches ) == 0 {
return fmt . Errorf ( "missing `match[]` arg" )
}
2019-10-15 16:12:27 +00:00
lookbackDelta , err := getMaxLookback ( r )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2019-10-15 16:12:27 +00:00
if lookbackDelta <= 0 {
lookbackDelta = defaultStep
}
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "start" , ct - lookbackDelta )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
end , err := searchutils . GetTime ( r , "end" , ct )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-05-22 21:16:55 +00:00
if start >= end {
start = end - defaultStep
}
tagFilterss , err := getTagFilterssFromMatches ( matches )
if err != nil {
return err
}
sq := & storage . SearchQuery {
2019-05-22 21:23:23 +00:00
AccountID : at . AccountID ,
ProjectID : at . ProjectID ,
2019-05-22 21:16:55 +00:00
MinTimestamp : start ,
MaxTimestamp : end ,
TagFilterss : tagFilterss ,
}
2019-08-04 19:15:33 +00:00
rss , isPartial , err := netstorage . ProcessSearchQuery ( at , sq , true , deadline )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot fetch data for %q: %w" , sq , err )
2019-05-22 21:16:55 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2020-09-03 23:23:12 +00:00
rss . Cancel ( )
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
2019-05-22 21:16:55 +00:00
resultsCh := make ( chan * quicktemplate . ByteBuffer )
doneCh := make ( chan error )
go func ( ) {
2019-07-12 12:51:02 +00:00
err := rss . RunParallel ( func ( rs * netstorage . Result , workerID uint ) {
2019-05-22 21:16:55 +00:00
bb := quicktemplate . AcquireByteBuffer ( )
WriteFederate ( bb , rs )
resultsCh <- bb
} )
close ( resultsCh )
doneCh <- err
} ( )
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
for bb := range resultsCh {
w . Write ( bb . B )
quicktemplate . ReleaseByteBuffer ( bb )
}
err = <- doneCh
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error during data fetching: %w" , err )
2019-05-22 21:16:55 +00:00
}
federateDuration . UpdateDuration ( startTime )
return nil
}
var federateDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/federate"} ` )
// ExportHandler exports data in raw format from /api/v1/export.
2020-02-04 14:13:59 +00:00
func ExportHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2019-05-22 21:16:55 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse request form values: %w" , err )
2019-05-22 21:16:55 +00:00
}
matches := r . Form [ "match[]" ]
if len ( matches ) == 0 {
// Maintain backwards compatibility
match := r . FormValue ( "match" )
2019-06-20 11:05:07 +00:00
if len ( match ) == 0 {
return fmt . Errorf ( "missing `match[]` arg" )
}
2019-05-22 21:16:55 +00:00
matches = [ ] string { match }
}
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "start" , 0 )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
end , err := searchutils . GetTime ( r , "end" , ct )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2019-05-22 21:16:55 +00:00
format := r . FormValue ( "format" )
2020-03-10 19:45:15 +00:00
maxRowsPerLine := int ( fastfloat . ParseInt64BestEffort ( r . FormValue ( "max_rows_per_line" ) ) )
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForExport ( r , startTime )
2019-05-22 21:16:55 +00:00
if start >= end {
2019-11-22 14:10:33 +00:00
end = start + defaultStep
2019-05-22 21:16:55 +00:00
}
2020-06-12 19:00:39 +00:00
if err := exportHandler ( at , w , r , matches , start , end , format , maxRowsPerLine , deadline ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error when exporting data for queries=%q on the time range (start=%d, end=%d): %w" , matches , start , end , err )
2019-05-22 21:16:55 +00:00
}
exportDuration . UpdateDuration ( startTime )
return nil
}
var exportDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/export"} ` )
2020-06-12 19:00:39 +00:00
func exportHandler ( at * auth . Token , w http . ResponseWriter , r * http . Request , matches [ ] string , start , end int64 , format string , maxRowsPerLine int , deadline netstorage . Deadline ) error {
2019-05-22 21:16:55 +00:00
writeResponseFunc := WriteExportStdResponse
2020-08-10 17:57:18 +00:00
writeLineFunc := func ( rs * netstorage . Result , resultsCh chan <- * quicktemplate . ByteBuffer ) {
bb := quicktemplate . AcquireByteBuffer ( )
WriteExportJSONLine ( bb , rs )
resultsCh <- bb
}
2020-03-10 19:45:15 +00:00
if maxRowsPerLine > 0 {
2020-08-10 17:57:18 +00:00
writeLineFunc = func ( rs * netstorage . Result , resultsCh chan <- * quicktemplate . ByteBuffer ) {
2020-03-10 19:45:15 +00:00
valuesOrig := rs . Values
timestampsOrig := rs . Timestamps
values := valuesOrig
timestamps := timestampsOrig
for len ( values ) > 0 {
var valuesChunk [ ] float64
var timestampsChunk [ ] int64
if len ( values ) > maxRowsPerLine {
valuesChunk = values [ : maxRowsPerLine ]
timestampsChunk = timestamps [ : maxRowsPerLine ]
values = values [ maxRowsPerLine : ]
timestamps = timestamps [ maxRowsPerLine : ]
} else {
valuesChunk = values
timestampsChunk = timestamps
values = nil
timestamps = nil
}
rs . Values = valuesChunk
rs . Timestamps = timestampsChunk
2020-08-10 17:57:18 +00:00
bb := quicktemplate . AcquireByteBuffer ( )
WriteExportJSONLine ( bb , rs )
resultsCh <- bb
2020-03-10 19:45:15 +00:00
}
rs . Values = valuesOrig
rs . Timestamps = timestampsOrig
}
}
2019-11-26 15:44:24 +00:00
contentType := "application/stream+json"
2019-05-22 21:16:55 +00:00
if format == "prometheus" {
contentType = "text/plain"
2020-08-10 17:57:18 +00:00
writeLineFunc = func ( rs * netstorage . Result , resultsCh chan <- * quicktemplate . ByteBuffer ) {
bb := quicktemplate . AcquireByteBuffer ( )
WriteExportPrometheusLine ( bb , rs )
resultsCh <- bb
}
2019-05-22 21:16:55 +00:00
} else if format == "promapi" {
writeResponseFunc = WriteExportPromAPIResponse
2020-08-10 17:57:18 +00:00
writeLineFunc = func ( rs * netstorage . Result , resultsCh chan <- * quicktemplate . ByteBuffer ) {
bb := quicktemplate . AcquireByteBuffer ( )
WriteExportPromAPILine ( bb , rs )
resultsCh <- bb
}
2019-05-22 21:16:55 +00:00
}
tagFilterss , err := getTagFilterssFromMatches ( matches )
if err != nil {
return err
}
sq := & storage . SearchQuery {
2019-05-22 21:23:23 +00:00
AccountID : at . AccountID ,
ProjectID : at . ProjectID ,
2019-05-22 21:16:55 +00:00
MinTimestamp : start ,
MaxTimestamp : end ,
TagFilterss : tagFilterss ,
}
2019-08-04 19:15:33 +00:00
rss , isPartial , err := netstorage . ProcessSearchQuery ( at , sq , true , deadline )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot fetch data for %q: %w" , sq , err )
2019-05-22 21:16:55 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2019-05-22 21:23:23 +00:00
rss . Cancel ( )
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
2019-05-22 21:23:23 +00:00
}
2019-05-22 21:16:55 +00:00
resultsCh := make ( chan * quicktemplate . ByteBuffer , runtime . GOMAXPROCS ( - 1 ) )
doneCh := make ( chan error )
go func ( ) {
2019-07-12 12:51:02 +00:00
err := rss . RunParallel ( func ( rs * netstorage . Result , workerID uint ) {
2020-08-10 17:57:18 +00:00
writeLineFunc ( rs , resultsCh )
2019-05-22 21:16:55 +00:00
} )
close ( resultsCh )
doneCh <- err
} ( )
w . Header ( ) . Set ( "Content-Type" , contentType )
writeResponseFunc ( w , resultsCh )
2019-05-24 11:54:31 +00:00
// Consume all the data from resultsCh in the event writeResponseFunc
// fails to consume all the data.
for bb := range resultsCh {
quicktemplate . ReleaseByteBuffer ( bb )
}
2019-05-22 21:16:55 +00:00
err = <- doneCh
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error during data fetching: %w" , err )
2019-05-22 21:16:55 +00:00
}
return nil
}
// DeleteHandler processes /api/v1/admin/tsdb/delete_series prometheus API request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#delete-series
2020-02-04 14:13:59 +00:00
func DeleteHandler ( startTime time . Time , at * auth . Token , r * http . Request ) error {
2019-05-22 21:16:55 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse request form values: %w" , err )
2019-05-22 21:16:55 +00:00
}
if r . FormValue ( "start" ) != "" || r . FormValue ( "end" ) != "" {
return fmt . Errorf ( "start and end aren't supported. Remove these args from the query in order to delete all the matching metrics" )
}
matches := r . Form [ "match[]" ]
2019-06-20 11:05:07 +00:00
if len ( matches ) == 0 {
return fmt . Errorf ( "missing `match[]` arg" )
}
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-05-22 21:16:55 +00:00
tagFilterss , err := getTagFilterssFromMatches ( matches )
if err != nil {
return err
}
sq := & storage . SearchQuery {
2019-05-22 21:23:23 +00:00
AccountID : at . AccountID ,
ProjectID : at . ProjectID ,
2019-05-22 21:16:55 +00:00
TagFilterss : tagFilterss ,
}
2019-05-22 21:23:23 +00:00
deletedCount , err := netstorage . DeleteSeries ( at , sq , deadline )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot delete time series matching %q: %w" , matches , err )
2019-05-22 21:16:55 +00:00
}
if deletedCount > 0 {
2019-05-22 21:23:23 +00:00
// Reset rollup result cache on all the vmselect nodes,
// since the cache may contain deleted data.
// TODO: reset only cache for (account, project)
resetRollupResultCaches ( )
2019-05-22 21:16:55 +00:00
}
deleteDuration . UpdateDuration ( startTime )
return nil
}
var deleteDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/admin/tsdb/delete_series"} ` )
2019-05-22 21:23:23 +00:00
func resetRollupResultCaches ( ) {
2019-06-18 07:26:44 +00:00
if len ( * selectNodes ) == 0 {
2019-05-22 21:23:23 +00:00
logger . Panicf ( "BUG: missing -selectNode flag" )
}
2019-06-18 07:26:44 +00:00
for _ , selectNode := range * selectNodes {
2019-05-22 21:23:23 +00:00
callURL := fmt . Sprintf ( "http://%s/internal/resetRollupResultCache" , selectNode )
resp , err := httpClient . Get ( callURL )
if err != nil {
logger . Errorf ( "error when accessing %q: %s" , callURL , err )
resetRollupResultCacheErrors . Inc ( )
continue
}
if resp . StatusCode != http . StatusOK {
_ = resp . Body . Close ( )
logger . Errorf ( "unexpected status code at %q; got %d; want %d" , callURL , resp . StatusCode , http . StatusOK )
resetRollupResultCacheErrors . Inc ( )
continue
}
_ = resp . Body . Close ( )
}
resetRollupResultCacheCalls . Inc ( )
}
var (
resetRollupResultCacheErrors = metrics . NewCounter ( "vm_reset_rollup_result_cache_errors_total" )
resetRollupResultCacheCalls = metrics . NewCounter ( "vm_reset_rollup_result_cache_calls_total" )
)
var httpClient = & http . Client {
Timeout : time . Second * 5 ,
}
2019-05-22 21:16:55 +00:00
// LabelValuesHandler processes /api/v1/label/<labelName>/values request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values
2020-02-04 14:13:59 +00:00
func LabelValuesHandler ( startTime time . Time , at * auth . Token , labelName string , w http . ResponseWriter , r * http . Request ) error {
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-08-04 20:06:55 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse form values: %w" , err )
2019-08-04 20:06:55 +00:00
}
var labelValues [ ] string
var isPartial bool
if len ( r . Form [ "match[]" ] ) == 0 && len ( r . Form [ "start" ] ) == 0 && len ( r . Form [ "end" ] ) == 0 {
var err error
labelValues , isPartial , err = netstorage . GetLabelValues ( at , labelName , deadline )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( ` cannot obtain label values for %q: %w ` , labelName , err )
2019-08-04 20:06:55 +00:00
}
} else {
// Extended functionality that allows filtering by label filters and time range
// i.e. /api/v1/label/foo/values?match[]=foobar{baz="abc"}&start=...&end=...
// is equivalent to `label_values(foobar{baz="abc"}, foo)` call on the selected
// time range in Grafana templating.
matches := r . Form [ "match[]" ]
if len ( matches ) == 0 {
matches = [ ] string { fmt . Sprintf ( "{%s!=''}" , labelName ) }
}
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2020-09-10 21:29:26 +00:00
end , err := searchutils . GetTime ( r , "end" , ct )
2019-08-04 20:06:55 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "start" , end - defaultStep )
2019-08-04 20:06:55 +00:00
if err != nil {
return err
}
labelValues , isPartial , err = labelValuesWithMatches ( at , labelName , matches , start , end , deadline )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot obtain label values for %q, match[]=%q, start=%d, end=%d: %w" , labelName , matches , start , end , err )
2019-08-04 20:06:55 +00:00
}
2019-05-22 21:16:55 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
2019-05-22 21:16:55 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteLabelValuesResponse ( w , labelValues )
labelValuesDuration . UpdateDuration ( startTime )
return nil
}
2019-08-04 20:06:55 +00:00
func labelValuesWithMatches ( at * auth . Token , labelName string , matches [ ] string , start , end int64 , deadline netstorage . Deadline ) ( [ ] string , bool , error ) {
if len ( matches ) == 0 {
logger . Panicf ( "BUG: matches must be non-empty" )
}
tagFilterss , err := getTagFilterssFromMatches ( matches )
if err != nil {
return nil , false , err
}
2020-02-28 21:35:47 +00:00
2020-02-28 10:17:27 +00:00
// Add `labelName!=''` tag filter in order to filter out series without the labelName.
2020-02-28 21:35:47 +00:00
// There is no need in adding `__name__!=''` filter, since all the time series should
// already have non-empty name.
if labelName != "__name__" {
key := [ ] byte ( labelName )
for i , tfs := range tagFilterss {
tagFilterss [ i ] = append ( tfs , storage . TagFilter {
Key : key ,
IsNegative : true ,
} )
}
2019-12-14 22:07:09 +00:00
}
2019-08-04 20:06:55 +00:00
if start >= end {
2019-11-22 14:10:33 +00:00
end = start + defaultStep
2019-08-04 20:06:55 +00:00
}
sq := & storage . SearchQuery {
AccountID : at . AccountID ,
ProjectID : at . ProjectID ,
MinTimestamp : start ,
MaxTimestamp : end ,
TagFilterss : tagFilterss ,
}
rss , isPartial , err := netstorage . ProcessSearchQuery ( at , sq , false , deadline )
if err != nil {
2020-06-30 19:58:18 +00:00
return nil , false , fmt . Errorf ( "cannot fetch data for %q: %w" , sq , err )
2019-08-04 20:06:55 +00:00
}
m := make ( map [ string ] struct { } )
var mLock sync . Mutex
err = rss . RunParallel ( func ( rs * netstorage . Result , workerID uint ) {
labelValue := rs . MetricName . GetTagValue ( labelName )
if len ( labelValue ) == 0 {
return
}
mLock . Lock ( )
m [ string ( labelValue ) ] = struct { } { }
mLock . Unlock ( )
} )
if err != nil {
2020-06-30 19:58:18 +00:00
return nil , false , fmt . Errorf ( "error when data fetching: %w" , err )
2019-08-04 20:06:55 +00:00
}
labelValues := make ( [ ] string , 0 , len ( m ) )
for labelValue := range m {
labelValues = append ( labelValues , labelValue )
}
sort . Strings ( labelValues )
return labelValues , isPartial , nil
}
2019-05-22 21:16:55 +00:00
var labelValuesDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/label/ { }/values"} ` )
2019-06-10 15:55:20 +00:00
// LabelsCountHandler processes /api/v1/labels/count request.
2020-02-04 14:13:59 +00:00
func LabelsCountHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-06-29 22:27:03 +00:00
labelEntries , isPartial , err := netstorage . GetLabelEntries ( at , deadline )
2019-06-10 15:55:20 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( ` cannot obtain label entries: %w ` , err )
2019-06-10 15:55:20 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
2019-06-10 15:55:20 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteLabelsCountResponse ( w , labelEntries )
labelsCountDuration . UpdateDuration ( startTime )
return nil
}
var labelsCountDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/labels/count"} ` )
2020-04-22 16:57:36 +00:00
const secsPerDay = 3600 * 24
// TSDBStatusHandler processes /api/v1/status/tsdb request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-stats
func TSDBStatusHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2020-04-22 16:57:36 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse form values: %w" , err )
2020-04-22 16:57:36 +00:00
}
2020-05-14 19:01:51 +00:00
date := fasttime . UnixDate ( )
2020-04-22 16:57:36 +00:00
dateStr := r . FormValue ( "date" )
if len ( dateStr ) > 0 {
t , err := time . Parse ( "2006-01-02" , dateStr )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse `date` arg %q: %w" , dateStr , err )
2020-04-22 16:57:36 +00:00
}
2020-05-14 19:01:51 +00:00
date = uint64 ( t . Unix ( ) ) / secsPerDay
2020-04-22 16:57:36 +00:00
}
topN := 10
topNStr := r . FormValue ( "topN" )
if len ( topNStr ) > 0 {
n , err := strconv . Atoi ( topNStr )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse `topN` arg %q: %w" , topNStr , err )
2020-04-22 16:57:36 +00:00
}
if n <= 0 {
n = 1
}
if n > 1000 {
n = 1000
}
topN = n
}
2020-05-14 19:01:51 +00:00
status , isPartial , err := netstorage . GetTSDBStatusForDate ( at , deadline , date , topN )
2020-04-22 16:57:36 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( ` cannot obtain tsdb status for date=%d, topN=%d: %w ` , date , topN , err )
2020-04-22 16:57:36 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2020-04-22 16:57:36 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteTSDBStatusResponse ( w , status )
tsdbStatusDuration . UpdateDuration ( startTime )
return nil
}
var tsdbStatusDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/status/tsdb"} ` )
2019-05-22 21:16:55 +00:00
// LabelsHandler processes /api/v1/labels request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names
2020-02-04 14:13:59 +00:00
func LabelsHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-12-14 22:07:09 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse form values: %w" , err )
2019-12-14 22:07:09 +00:00
}
var labels [ ] string
var isPartial bool
if len ( r . Form [ "match[]" ] ) == 0 && len ( r . Form [ "start" ] ) == 0 && len ( r . Form [ "end" ] ) == 0 {
var err error
labels , isPartial , err = netstorage . GetLabels ( at , deadline )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot obtain labels: %w" , err )
2019-12-14 22:07:09 +00:00
}
} else {
// Extended functionality that allows filtering by label filters and time range
// i.e. /api/v1/labels?match[]=foobar{baz="abc"}&start=...&end=...
matches := r . Form [ "match[]" ]
if len ( matches ) == 0 {
matches = [ ] string { "{__name__!=''}" }
}
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2020-09-10 21:29:26 +00:00
end , err := searchutils . GetTime ( r , "end" , ct )
2019-12-14 22:07:09 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "start" , end - defaultStep )
2019-12-14 22:07:09 +00:00
if err != nil {
return err
}
labels , isPartial , err = labelsWithMatches ( at , matches , start , end , deadline )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot obtain labels for match[]=%q, start=%d, end=%d: %w" , matches , start , end , err )
2019-12-14 22:07:09 +00:00
}
2019-05-22 21:16:55 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
2019-05-22 21:16:55 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteLabelsResponse ( w , labels )
labelsDuration . UpdateDuration ( startTime )
return nil
}
2019-12-14 22:07:09 +00:00
func labelsWithMatches ( at * auth . Token , matches [ ] string , start , end int64 , deadline netstorage . Deadline ) ( [ ] string , bool , error ) {
if len ( matches ) == 0 {
logger . Panicf ( "BUG: matches must be non-empty" )
}
tagFilterss , err := getTagFilterssFromMatches ( matches )
if err != nil {
return nil , false , err
}
if start >= end {
end = start + defaultStep
}
sq := & storage . SearchQuery {
AccountID : at . AccountID ,
ProjectID : at . ProjectID ,
MinTimestamp : start ,
MaxTimestamp : end ,
TagFilterss : tagFilterss ,
}
rss , isPartial , err := netstorage . ProcessSearchQuery ( at , sq , false , deadline )
if err != nil {
2020-06-30 19:58:18 +00:00
return nil , false , fmt . Errorf ( "cannot fetch data for %q: %w" , sq , err )
2019-12-14 22:07:09 +00:00
}
m := make ( map [ string ] struct { } )
var mLock sync . Mutex
err = rss . RunParallel ( func ( rs * netstorage . Result , workerID uint ) {
mLock . Lock ( )
tags := rs . MetricName . Tags
for i := range tags {
t := & tags [ i ]
m [ string ( t . Key ) ] = struct { } { }
}
m [ "__name__" ] = struct { } { }
mLock . Unlock ( )
} )
if err != nil {
2020-06-30 19:58:18 +00:00
return nil , false , fmt . Errorf ( "error when data fetching: %w" , err )
2019-12-14 22:07:09 +00:00
}
labels := make ( [ ] string , 0 , len ( m ) )
for label := range m {
labels = append ( labels , label )
}
sort . Strings ( labels )
return labels , isPartial , nil
}
2019-05-22 21:16:55 +00:00
var labelsDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/labels"} ` )
// SeriesCountHandler processes /api/v1/series/count request.
2020-02-04 14:13:59 +00:00
func SeriesCountHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-06-29 22:27:03 +00:00
n , isPartial , err := netstorage . GetSeriesCount ( at , deadline )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot obtain series count: %w" , err )
2019-05-22 21:16:55 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
2019-05-22 21:23:23 +00:00
2019-05-22 21:16:55 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteSeriesCountResponse ( w , n )
seriesCountDuration . UpdateDuration ( startTime )
return nil
}
var seriesCountDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/series/count"} ` )
// SeriesHandler processes /api/v1/series request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#finding-series-by-label-matchers
2020-02-04 14:13:59 +00:00
func SeriesHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2019-05-22 21:16:55 +00:00
if err := r . ParseForm ( ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse form values: %w" , err )
2019-05-22 21:16:55 +00:00
}
matches := r . Form [ "match[]" ]
2019-06-20 11:05:07 +00:00
if len ( matches ) == 0 {
return fmt . Errorf ( "missing `match[]` arg" )
}
2020-09-10 21:29:26 +00:00
end , err := searchutils . GetTime ( r , "end" , ct )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
// Do not set start to searchutils.minTimeMsecs by default as Prometheus does,
2019-08-04 16:42:36 +00:00
// since this leads to fetching and scanning all the data from the storage,
// which can take a lot of time for big storages.
// It is better setting start as end-defaultStep by default.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/91
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "start" , end - defaultStep )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-05-22 21:16:55 +00:00
tagFilterss , err := getTagFilterssFromMatches ( matches )
if err != nil {
return err
}
if start >= end {
2019-11-22 14:10:33 +00:00
end = start + defaultStep
2019-05-22 21:16:55 +00:00
}
sq := & storage . SearchQuery {
2019-05-22 21:23:23 +00:00
AccountID : at . AccountID ,
ProjectID : at . ProjectID ,
2019-05-22 21:16:55 +00:00
MinTimestamp : start ,
MaxTimestamp : end ,
TagFilterss : tagFilterss ,
}
2019-08-04 19:15:33 +00:00
rss , isPartial , err := netstorage . ProcessSearchQuery ( at , sq , false , deadline )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot fetch data for %q: %w" , sq , err )
2019-05-22 21:16:55 +00:00
}
2020-09-10 21:29:26 +00:00
if isPartial && searchutils . GetDenyPartialResponse ( r ) {
2020-09-03 23:23:12 +00:00
rss . Cancel ( )
2019-06-29 22:27:03 +00:00
return fmt . Errorf ( "cannot return full response, since some of vmstorage nodes are unavailable" )
}
2019-05-22 21:16:55 +00:00
resultsCh := make ( chan * quicktemplate . ByteBuffer )
doneCh := make ( chan error )
go func ( ) {
2019-07-12 12:51:02 +00:00
err := rss . RunParallel ( func ( rs * netstorage . Result , workerID uint ) {
2019-05-22 21:16:55 +00:00
bb := quicktemplate . AcquireByteBuffer ( )
writemetricNameObject ( bb , & rs . MetricName )
resultsCh <- bb
} )
close ( resultsCh )
doneCh <- err
} ( )
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteSeriesResponse ( w , resultsCh )
// Consume all the data from resultsCh in the event WriteSeriesResponse
2019-05-24 11:54:31 +00:00
// fails to consume all the data.
2019-05-22 21:16:55 +00:00
for bb := range resultsCh {
quicktemplate . ReleaseByteBuffer ( bb )
}
err = <- doneCh
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error during data fetching: %w" , err )
2019-05-22 21:16:55 +00:00
}
seriesDuration . UpdateDuration ( startTime )
return nil
}
var seriesDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/series"} ` )
// QueryHandler processes /api/v1/query request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries
2020-02-04 14:13:59 +00:00
func QueryHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2019-05-22 21:16:55 +00:00
query := r . FormValue ( "query" )
2019-06-20 11:05:07 +00:00
if len ( query ) == 0 {
return fmt . Errorf ( "missing `query` arg" )
}
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "time" , ct )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-04-17 09:24:10 +00:00
lookbackDelta , err := getMaxLookback ( r )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
step , err := searchutils . GetDuration ( r , "step" , lookbackDelta )
2019-10-15 16:12:27 +00:00
if err != nil {
return err
}
2020-04-17 09:24:10 +00:00
if step <= 0 {
step = defaultStep
}
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
2019-05-22 21:16:55 +00:00
2020-08-16 14:05:52 +00:00
if len ( query ) > maxQueryLen . N {
return fmt . Errorf ( "too long query; got %d bytes; mustn't exceed `-search.maxQueryLen=%d` bytes" , len ( query ) , maxQueryLen . N )
2019-05-22 21:16:55 +00:00
}
2020-03-29 18:50:10 +00:00
queryOffset := getLatencyOffsetMilliseconds ( )
2020-09-10 21:29:26 +00:00
if ! searchutils . GetBool ( r , "nocache" ) && ct - start < queryOffset {
2019-11-26 20:55:23 +00:00
// Adjust start time only if `nocache` arg isn't set.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/241
2019-11-18 22:41:13 +00:00
start = ct - queryOffset
2019-05-22 21:16:55 +00:00
}
if childQuery , windowStr , offsetStr := promql . IsMetricSelectorWithRollup ( query ) ; childQuery != "" {
2019-12-10 22:42:44 +00:00
window , err := parsePositiveDuration ( windowStr , step )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse window: %w" , err )
2019-05-22 21:16:55 +00:00
}
2019-12-10 22:42:44 +00:00
offset , err := parseDuration ( offsetStr , step )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse offset: %w" , err )
2019-05-22 21:16:55 +00:00
}
start -= offset
end := start
start = end - window
2020-06-12 19:00:39 +00:00
if err := exportHandler ( at , w , r , [ ] string { childQuery } , start , end , "promapi" , 0 , deadline ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error when exporting data for query=%q on the time range (start=%d, end=%d): %w" , childQuery , start , end , err )
2019-05-22 21:16:55 +00:00
}
queryDuration . UpdateDuration ( startTime )
return nil
}
2019-12-10 22:42:44 +00:00
if childQuery , windowStr , stepStr , offsetStr := promql . IsRollup ( query ) ; childQuery != "" {
newStep , err := parsePositiveDuration ( stepStr , step )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse step: %w" , err )
2019-12-10 22:42:44 +00:00
}
if newStep > 0 {
step = newStep
}
window , err := parsePositiveDuration ( windowStr , step )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse window: %w" , err )
2019-12-10 22:42:44 +00:00
}
offset , err := parseDuration ( offsetStr , step )
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot parse offset: %w" , err )
2019-12-10 22:42:44 +00:00
}
start -= offset
end := start
start = end - window
2020-07-21 15:34:59 +00:00
if err := queryRangeHandler ( startTime , at , w , childQuery , start , end , step , r , ct ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error when executing query=%q on the time range (start=%d, end=%d, step=%d): %w" , childQuery , start , end , step , err )
2019-12-10 22:42:44 +00:00
}
queryDuration . UpdateDuration ( startTime )
return nil
}
2019-05-22 21:16:55 +00:00
ec := promql . EvalConfig {
2020-07-31 15:00:21 +00:00
AuthToken : at ,
Start : start ,
End : start ,
Step : step ,
QuotedRemoteAddr : httpserver . GetQuotedRemoteAddr ( r ) ,
Deadline : deadline ,
LookbackDelta : lookbackDelta ,
2019-06-29 22:27:03 +00:00
2020-09-10 21:29:26 +00:00
DenyPartialResponse : searchutils . GetDenyPartialResponse ( r ) ,
2019-05-22 21:16:55 +00:00
}
2019-07-01 14:14:49 +00:00
result , err := promql . Exec ( & ec , query , true )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error when executing query=%q for (time=%d, step=%d): %w" , query , start , step , err )
2019-05-22 21:16:55 +00:00
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteQueryResponse ( w , result )
queryDuration . UpdateDuration ( startTime )
return nil
}
var queryDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/query"} ` )
2019-12-10 22:42:44 +00:00
func parseDuration ( s string , step int64 ) ( int64 , error ) {
if len ( s ) == 0 {
return 0 , nil
}
2019-12-25 19:35:47 +00:00
return metricsql . DurationValue ( s , step )
2019-12-10 22:42:44 +00:00
}
func parsePositiveDuration ( s string , step int64 ) ( int64 , error ) {
if len ( s ) == 0 {
return 0 , nil
}
2019-12-25 19:35:47 +00:00
return metricsql . PositiveDurationValue ( s , step )
2019-12-10 22:42:44 +00:00
}
2019-05-22 21:16:55 +00:00
// QueryRangeHandler processes /api/v1/query_range request.
//
// See https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries
2020-02-04 14:13:59 +00:00
func QueryRangeHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , r * http . Request ) error {
2020-07-21 15:34:59 +00:00
ct := startTime . UnixNano ( ) / 1e6
2019-05-22 21:16:55 +00:00
query := r . FormValue ( "query" )
2019-06-20 11:05:07 +00:00
if len ( query ) == 0 {
return fmt . Errorf ( "missing `query` arg" )
}
2020-09-10 21:29:26 +00:00
start , err := searchutils . GetTime ( r , "start" , ct - defaultStep )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
end , err := searchutils . GetTime ( r , "end" , ct )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-09-10 21:29:26 +00:00
step , err := searchutils . GetDuration ( r , "step" , defaultStep )
2019-06-06 19:17:13 +00:00
if err != nil {
return err
}
2020-07-21 15:34:59 +00:00
if err := queryRangeHandler ( startTime , at , w , query , start , end , step , r , ct ) ; err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "error when executing query=%q on the time range (start=%d, end=%d, step=%d): %w" , query , start , end , step , err )
2019-12-10 22:42:44 +00:00
}
queryRangeDuration . UpdateDuration ( startTime )
return nil
}
2020-07-21 15:34:59 +00:00
func queryRangeHandler ( startTime time . Time , at * auth . Token , w http . ResponseWriter , query string , start , end , step int64 , r * http . Request , ct int64 ) error {
2020-09-10 21:29:26 +00:00
deadline := searchutils . GetDeadlineForQuery ( r , startTime )
mayCache := ! searchutils . GetBool ( r , "nocache" )
2019-10-15 16:12:27 +00:00
lookbackDelta , err := getMaxLookback ( r )
if err != nil {
return err
}
2019-05-22 21:16:55 +00:00
// Validate input args.
2020-08-16 14:05:52 +00:00
if len ( query ) > maxQueryLen . N {
return fmt . Errorf ( "too long query; got %d bytes; mustn't exceed `-search.maxQueryLen=%d` bytes" , len ( query ) , maxQueryLen . N )
2019-05-22 21:16:55 +00:00
}
if start > end {
2019-11-22 14:10:33 +00:00
end = start + defaultStep
2019-05-22 21:16:55 +00:00
}
if err := promql . ValidateMaxPointsPerTimeseries ( start , end , step ) ; err != nil {
return err
}
2019-09-04 10:09:20 +00:00
if mayCache {
start , end = promql . AdjustStartEnd ( start , end , step )
}
2019-05-22 21:16:55 +00:00
ec := promql . EvalConfig {
2020-07-31 15:00:21 +00:00
AuthToken : at ,
Start : start ,
End : end ,
Step : step ,
QuotedRemoteAddr : httpserver . GetQuotedRemoteAddr ( r ) ,
Deadline : deadline ,
MayCache : mayCache ,
LookbackDelta : lookbackDelta ,
2019-06-29 22:27:03 +00:00
2020-09-10 21:29:26 +00:00
DenyPartialResponse : searchutils . GetDenyPartialResponse ( r ) ,
2019-05-22 21:16:55 +00:00
}
2019-07-01 14:14:49 +00:00
result , err := promql . Exec ( & ec , query , false )
2019-05-22 21:16:55 +00:00
if err != nil {
2020-06-30 19:58:18 +00:00
return fmt . Errorf ( "cannot execute query: %w" , err )
2019-05-22 21:16:55 +00:00
}
2019-10-28 10:30:50 +00:00
queryOffset := getLatencyOffsetMilliseconds ( )
2020-07-05 15:17:02 +00:00
if ct - queryOffset < end {
2020-07-14 09:45:42 +00:00
result = adjustLastPoints ( result , ct - queryOffset , ct + step )
2019-05-22 21:16:55 +00:00
}
2019-08-20 19:52:49 +00:00
// Remove NaN values as Prometheus does.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/153
2020-07-20 12:28:36 +00:00
result = removeEmptyValuesAndTimeseries ( result )
2019-08-20 19:52:49 +00:00
2019-05-22 21:16:55 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
WriteQueryRangeResponse ( w , result )
return nil
}
2020-07-20 12:28:36 +00:00
func removeEmptyValuesAndTimeseries ( tss [ ] netstorage . Result ) [ ] netstorage . Result {
dst := tss [ : 0 ]
2019-08-20 19:52:49 +00:00
for i := range tss {
ts := & tss [ i ]
hasNaNs := false
for _ , v := range ts . Values {
if math . IsNaN ( v ) {
hasNaNs = true
break
}
}
if ! hasNaNs {
// Fast path: nothing to remove.
2020-07-20 12:28:36 +00:00
if len ( ts . Values ) > 0 {
dst = append ( dst , * ts )
}
2019-08-20 19:52:49 +00:00
continue
}
// Slow path: remove NaNs.
srcTimestamps := ts . Timestamps
dstValues := ts . Values [ : 0 ]
dstTimestamps := ts . Timestamps [ : 0 ]
for j , v := range ts . Values {
if math . IsNaN ( v ) {
continue
}
dstValues = append ( dstValues , v )
dstTimestamps = append ( dstTimestamps , srcTimestamps [ j ] )
}
ts . Values = dstValues
ts . Timestamps = dstTimestamps
2020-07-20 12:28:36 +00:00
if len ( ts . Values ) > 0 {
dst = append ( dst , * ts )
}
2019-08-20 19:52:49 +00:00
}
2020-07-20 12:28:36 +00:00
return dst
2019-08-20 19:52:49 +00:00
}
2019-05-22 21:16:55 +00:00
var queryRangeDuration = metrics . NewSummary ( ` vm_request_duration_seconds { path="/api/v1/query_range"} ` )
2020-07-14 09:45:42 +00:00
var nan = math . NaN ( )
2020-07-05 15:17:02 +00:00
// adjustLastPoints substitutes the last point values on the time range (start..end]
2020-07-14 09:45:42 +00:00
// with the previous point values, since these points may contain incomplete values.
2020-07-05 15:17:02 +00:00
func adjustLastPoints ( tss [ ] netstorage . Result , start , end int64 ) [ ] netstorage . Result {
2019-05-22 21:16:55 +00:00
for i := range tss {
2020-07-05 15:17:02 +00:00
ts := & tss [ i ]
values := ts . Values
timestamps := ts . Timestamps
j := len ( timestamps ) - 1
2020-07-14 09:45:42 +00:00
if j >= 0 && timestamps [ j ] > end {
// It looks like the `offset` is used in the query, which shifts time range beyond the `end`.
// Leave such a time series as is, since it is unclear which points may be incomplete in it.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/625
continue
}
2020-07-05 15:17:02 +00:00
for j >= 0 && timestamps [ j ] > start {
2019-05-22 21:16:55 +00:00
j --
}
2020-07-05 15:17:02 +00:00
j ++
2020-07-14 09:45:42 +00:00
lastValue := nan
if j > 0 {
lastValue = values [ j - 1 ]
2020-07-05 14:56:54 +00:00
}
2020-07-05 15:17:02 +00:00
for j < len ( timestamps ) && timestamps [ j ] <= end {
2020-07-14 09:45:42 +00:00
values [ j ] = lastValue
2020-07-05 15:17:02 +00:00
j ++
2019-05-22 21:16:55 +00:00
}
}
2019-07-04 06:14:15 +00:00
return tss
2019-05-22 21:16:55 +00:00
}
2019-10-15 16:12:27 +00:00
func getMaxLookback ( r * http . Request ) ( int64 , error ) {
2020-03-29 18:50:10 +00:00
d := maxLookback . Milliseconds ( )
2020-04-20 16:25:32 +00:00
if d == 0 {
d = maxStalenessInterval . Milliseconds ( )
}
2020-09-10 21:29:26 +00:00
return searchutils . GetDuration ( r , "max_lookback" , d )
2019-05-22 21:16:55 +00:00
}
func getTagFilterssFromMatches ( matches [ ] string ) ( [ ] [ ] storage . TagFilter , error ) {
tagFilterss := make ( [ ] [ ] storage . TagFilter , 0 , len ( matches ) )
for _ , match := range matches {
tagFilters , err := promql . ParseMetricSelector ( match )
if err != nil {
2020-06-30 19:58:18 +00:00
return nil , fmt . Errorf ( "cannot parse %q: %w" , match , err )
2019-05-22 21:16:55 +00:00
}
tagFilterss = append ( tagFilterss , tagFilters )
}
return tagFilterss , nil
}
2019-06-29 22:27:03 +00:00
2019-10-28 10:30:50 +00:00
func getLatencyOffsetMilliseconds ( ) int64 {
2020-03-29 18:50:10 +00:00
d := latencyOffset . Milliseconds ( )
2019-10-28 10:30:50 +00:00
if d <= 1000 {
d = 1000
}
return d
}