2017-10-23 08:56:47 -07:00
// Copyright 2017 The Prometheus Authors
2017-10-23 06:44:57 -07:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package remote
import (
2022-07-01 09:59:50 -07:00
"errors"
2017-10-23 06:44:57 -07:00
"fmt"
2018-06-08 00:19:20 -07:00
"io"
2023-03-27 17:02:20 -07:00
"math"
2017-10-23 06:44:57 -07:00
"net/http"
2017-10-23 08:56:47 -07:00
"sort"
2020-11-19 07:23:03 -08:00
"strings"
2022-11-15 07:29:16 -08:00
"sync"
2017-10-23 06:44:57 -07:00
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/common/model"
2020-10-22 02:00:08 -07:00
2021-11-08 06:23:17 -08:00
"github.com/prometheus/prometheus/model/exemplar"
Style cleanup of all the changes in sparsehistogram so far
A lot of this code was hacked together, literally during a
hackathon. This commit intends not to change the code substantially,
but just make the code obey the usual style practices.
A (possibly incomplete) list of areas:
* Generally address linter warnings.
* The `pgk` directory is deprecated as per dev-summit. No new packages should
be added to it. I moved the new `pkg/histogram` package to `model`
anticipating what's proposed in #9478.
* Make the naming of the Sparse Histogram more consistent. Including
abbreviations, there were just too many names for it: SparseHistogram,
Histogram, Histo, hist, his, shs, h. The idea is to call it "Histogram" in
general. Only add "Sparse" if it is needed to avoid confusion with
conventional Histograms (which is rare because the TSDB really has no notion
of conventional Histograms). Use abbreviations only in local scope, and then
really abbreviate (not just removing three out of seven letters like in
"Histo"). This is in the spirit of
https://github.com/golang/go/wiki/CodeReviewComments#variable-names
* Several other minor name changes.
* A lot of formatting of doc comments. For one, following
https://github.com/golang/go/wiki/CodeReviewComments#comment-sentences
, but also layout question, anticipating how things will look like
when rendered by `godoc` (even where `godoc` doesn't render them
right now because they are for unexported types or not a doc comment
at all but just a normal code comment - consistency is queen!).
* Re-enabled `TestQueryLog` and `TestEndopints` (they pass now,
leaving them disabled was presumably an oversight).
* Bucket iterator for histogram.Histogram is now created with a
method.
* HistogramChunk.iterator now allows iterator recycling. (I think
@dieterbe only commented it out because he was confused by the
question in the comment.)
* HistogramAppender.Append panics now because we decided to treat
staleness marker differently.
Signed-off-by: beorn7 <beorn@grafana.com>
2021-10-09 06:57:07 -07:00
"github.com/prometheus/prometheus/model/histogram"
2021-11-08 06:23:17 -08:00
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/textparse"
2017-10-23 06:44:57 -07:00
"github.com/prometheus/prometheus/prompb"
2017-10-23 13:28:17 -07:00
"github.com/prometheus/prometheus/storage"
2019-08-19 13:16:10 -07:00
"github.com/prometheus/prometheus/tsdb/chunkenc"
2022-09-20 10:16:45 -07:00
"github.com/prometheus/prometheus/tsdb/chunks"
2017-10-23 06:44:57 -07:00
)
2018-06-08 00:19:20 -07:00
// decodeReadLimit is the maximum size of a read request body in bytes.
const decodeReadLimit = 32 * 1024 * 1024
2018-09-05 06:50:50 -07:00
type HTTPError struct {
msg string
status int
}
func ( e HTTPError ) Error ( ) string {
return e . msg
}
func ( e HTTPError ) Status ( ) int {
return e . status
}
2017-10-23 06:44:57 -07:00
// DecodeReadRequest reads a remote.Request from a http.Request.
func DecodeReadRequest ( r * http . Request ) ( * prompb . ReadRequest , error ) {
2022-04-27 02:24:36 -07:00
compressed , err := io . ReadAll ( io . LimitReader ( r . Body , decodeReadLimit ) )
2017-10-23 06:44:57 -07:00
if err != nil {
return nil , err
}
reqBuf , err := snappy . Decode ( nil , compressed )
if err != nil {
return nil , err
}
var req prompb . ReadRequest
if err := proto . Unmarshal ( reqBuf , & req ) ; err != nil {
return nil , err
}
return & req , nil
}
// EncodeReadResponse writes a remote.Response to a http.ResponseWriter.
func EncodeReadResponse ( resp * prompb . ReadResponse , w http . ResponseWriter ) error {
data , err := proto . Marshal ( resp )
if err != nil {
return err
}
compressed := snappy . Encode ( nil , data )
_ , err = w . Write ( compressed )
return err
}
// ToQuery builds a Query proto.
2020-03-12 02:36:09 -07:00
func ToQuery ( from , to int64 , matchers [ ] * labels . Matcher , hints * storage . SelectHints ) ( * prompb . Query , error ) {
2017-10-23 06:44:57 -07:00
ms , err := toLabelMatchers ( matchers )
if err != nil {
return nil , err
}
2018-06-18 08:33:04 -07:00
var rp * prompb . ReadHints
2020-03-12 02:36:09 -07:00
if hints != nil {
2018-06-13 00:19:17 -07:00
rp = & prompb . ReadHints {
2020-03-12 02:36:09 -07:00
StartMs : hints . Start ,
EndMs : hints . End ,
StepMs : hints . Step ,
Func : hints . Func ,
Grouping : hints . Grouping ,
By : hints . By ,
RangeMs : hints . Range ,
2018-06-13 00:19:17 -07:00
}
2018-05-08 01:48:13 -07:00
}
2017-10-23 06:44:57 -07:00
return & prompb . Query {
StartTimestampMs : from ,
EndTimestampMs : to ,
Matchers : ms ,
2018-05-08 01:48:13 -07:00
Hints : rp ,
2017-10-23 06:44:57 -07:00
} , nil
}
// ToQueryResult builds a QueryResult proto.
2020-06-09 09:57:31 -07:00
func ToQueryResult ( ss storage . SeriesSet , sampleLimit int ) ( * prompb . QueryResult , storage . Warnings , error ) {
2018-09-05 06:50:50 -07:00
numSamples := 0
2017-10-23 06:44:57 -07:00
resp := & prompb . QueryResult { }
2022-09-20 10:16:45 -07:00
var iter chunkenc . Iterator
2017-10-23 13:28:17 -07:00
for ss . Next ( ) {
series := ss . At ( )
2022-09-20 10:16:45 -07:00
iter = series . Iterator ( iter )
2017-10-23 13:28:17 -07:00
2023-03-07 12:21:55 -08:00
var (
samples [ ] prompb . Sample
histograms [ ] prompb . Histogram
)
for valType := iter . Next ( ) ; valType != chunkenc . ValNone ; valType = iter . Next ( ) {
2018-09-05 06:50:50 -07:00
numSamples ++
if sampleLimit > 0 && numSamples > sampleLimit {
2020-06-09 09:57:31 -07:00
return nil , ss . Warnings ( ) , HTTPError {
2018-09-05 06:50:50 -07:00
msg : fmt . Sprintf ( "exceeded sample limit (%d)" , sampleLimit ) ,
status : http . StatusBadRequest ,
}
}
2023-03-07 12:21:55 -08:00
switch valType {
case chunkenc . ValFloat :
ts , val := iter . At ( )
samples = append ( samples , prompb . Sample {
Timestamp : ts ,
Value : val ,
} )
case chunkenc . ValHistogram :
ts , h := iter . AtHistogram ( )
histograms = append ( histograms , HistogramToHistogramProto ( ts , h ) )
case chunkenc . ValFloatHistogram :
ts , fh := iter . AtFloatHistogram ( )
histograms = append ( histograms , FloatHistogramToHistogramProto ( ts , fh ) )
default :
return nil , ss . Warnings ( ) , fmt . Errorf ( "unrecognized value type: %s" , valType )
}
2017-10-23 06:44:57 -07:00
}
2017-10-23 13:28:17 -07:00
if err := iter . Err ( ) ; err != nil {
2020-06-09 09:57:31 -07:00
return nil , ss . Warnings ( ) , err
2017-10-23 13:28:17 -07:00
}
resp . Timeseries = append ( resp . Timeseries , & prompb . TimeSeries {
2023-03-07 12:21:55 -08:00
Labels : labelsToLabelsProto ( series . Labels ( ) , nil ) ,
Samples : samples ,
Histograms : histograms ,
2017-10-23 13:28:17 -07:00
} )
}
2020-06-24 06:41:52 -07:00
return resp , ss . Warnings ( ) , ss . Err ( )
2017-10-23 06:44:57 -07:00
}
2020-01-17 03:21:44 -08:00
// FromQueryResult unpacks and sorts a QueryResult proto.
2020-03-12 02:36:09 -07:00
func FromQueryResult ( sortSeries bool , res * prompb . QueryResult ) storage . SeriesSet {
2017-10-23 13:28:17 -07:00
series := make ( [ ] storage . Series , 0 , len ( res . Timeseries ) )
for _ , ts := range res . Timeseries {
2022-03-09 14:26:43 -08:00
if err := validateLabelsAndMetricName ( ts . Labels ) ; err != nil {
2017-10-23 13:28:17 -07:00
return errSeriesSet { err : err }
2017-10-23 06:44:57 -07:00
}
2022-03-09 14:26:43 -08:00
lbls := labelProtosToLabels ( ts . Labels )
2023-03-27 17:02:20 -07:00
series = append ( series , & concreteSeries { labels : lbls , floats : ts . Samples , histograms : ts . Histograms } )
2017-10-23 06:44:57 -07:00
}
2020-03-12 02:36:09 -07:00
if sortSeries {
sort . Sort ( byLabel ( series ) )
}
2017-10-23 13:28:17 -07:00
return & concreteSeriesSet {
series : series ,
}
}
2019-08-19 13:16:10 -07:00
// NegotiateResponseType returns first accepted response type that this server supports.
// On the empty accepted list we assume that the SAMPLES response type was requested. This is to maintain backward compatibility.
func NegotiateResponseType ( accepted [ ] prompb . ReadRequest_ResponseType ) ( prompb . ReadRequest_ResponseType , error ) {
if len ( accepted ) == 0 {
accepted = [ ] prompb . ReadRequest_ResponseType { prompb . ReadRequest_SAMPLES }
}
supported := map [ prompb . ReadRequest_ResponseType ] struct { } {
prompb . ReadRequest_SAMPLES : { } ,
prompb . ReadRequest_STREAMED_XOR_CHUNKS : { } ,
}
for _ , resType := range accepted {
if _ , ok := supported [ resType ] ; ok {
return resType , nil
}
}
2022-07-01 09:59:50 -07:00
return 0 , fmt . Errorf ( "server does not support any of the requested response types: %v; supported: %v" , accepted , supported )
2019-08-19 13:16:10 -07:00
}
2020-06-24 06:41:52 -07:00
// StreamChunkedReadResponses iterates over series, builds chunks and streams those to the caller.
// It expects Series set with populated chunks.
func StreamChunkedReadResponses (
stream io . Writer ,
queryIndex int64 ,
ss storage . ChunkSeriesSet ,
sortedExternalLabels [ ] prompb . Label ,
maxBytesInFrame int ,
2022-11-15 07:29:16 -08:00
marshalPool * sync . Pool ,
2020-06-24 06:41:52 -07:00
) ( storage . Warnings , error ) {
var (
chks [ ] prompb . Chunk
lbls [ ] prompb . Label
2022-09-20 10:16:45 -07:00
iter chunks . Iterator
2020-06-24 06:41:52 -07:00
)
for ss . Next ( ) {
series := ss . At ( )
2022-09-20 10:16:45 -07:00
iter = series . Iterator ( iter )
2020-06-24 06:41:52 -07:00
lbls = MergeLabels ( labelsToLabelsProto ( series . Labels ( ) , lbls ) , sortedExternalLabels )
2022-12-19 07:54:49 -08:00
maxDataLength := maxBytesInFrame
2020-06-24 06:41:52 -07:00
for _ , lbl := range lbls {
2022-12-19 07:54:49 -08:00
maxDataLength -= lbl . Size ( )
2020-06-24 06:41:52 -07:00
}
2022-12-19 07:54:49 -08:00
frameBytesLeft := maxDataLength
2020-06-24 06:41:52 -07:00
isNext := iter . Next ( )
// Send at most one series per frame; series may be split over multiple frames according to maxBytesInFrame.
for isNext {
chk := iter . At ( )
if chk . Chunk == nil {
2022-07-01 09:59:50 -07:00
return ss . Warnings ( ) , fmt . Errorf ( "StreamChunkedReadResponses: found not populated chunk returned by SeriesSet at ref: %v" , chk . Ref )
2020-06-24 06:41:52 -07:00
}
// Cut the chunk.
chks = append ( chks , prompb . Chunk {
MinTimeMs : chk . MinTime ,
MaxTimeMs : chk . MaxTime ,
Type : prompb . Chunk_Encoding ( chk . Chunk . Encoding ( ) ) ,
Data : chk . Chunk . Bytes ( ) ,
} )
frameBytesLeft -= chks [ len ( chks ) - 1 ] . Size ( )
// We are fine with minor inaccuracy of max bytes per frame. The inaccuracy will be max of full chunk size.
isNext = iter . Next ( )
if frameBytesLeft > 0 && isNext {
continue
}
2022-11-15 07:29:16 -08:00
resp := & prompb . ChunkedReadResponse {
2020-06-24 06:41:52 -07:00
ChunkedSeries : [ ] * prompb . ChunkedSeries {
{ Labels : lbls , Chunks : chks } ,
} ,
QueryIndex : queryIndex ,
2022-11-15 07:29:16 -08:00
}
b , err := resp . PooledMarshal ( marshalPool )
2020-06-24 06:41:52 -07:00
if err != nil {
2022-07-01 09:59:50 -07:00
return ss . Warnings ( ) , fmt . Errorf ( "marshal ChunkedReadResponse: %w" , err )
2020-06-24 06:41:52 -07:00
}
if _ , err := stream . Write ( b ) ; err != nil {
2022-07-01 09:59:50 -07:00
return ss . Warnings ( ) , fmt . Errorf ( "write to stream: %w" , err )
2020-06-24 06:41:52 -07:00
}
2022-11-15 07:29:16 -08:00
// We immediately flush the Write() so it is safe to return to the pool.
marshalPool . Put ( & b )
2020-06-24 06:41:52 -07:00
chks = chks [ : 0 ]
2022-12-19 07:54:49 -08:00
frameBytesLeft = maxDataLength
2020-06-24 06:41:52 -07:00
}
if err := iter . Err ( ) ; err != nil {
return ss . Warnings ( ) , err
}
}
return ss . Warnings ( ) , ss . Err ( )
}
2019-08-19 13:16:10 -07:00
// MergeLabels merges two sets of sorted proto labels, preferring those in
// primary to those in secondary when there is an overlap.
func MergeLabels ( primary , secondary [ ] prompb . Label ) [ ] prompb . Label {
result := make ( [ ] prompb . Label , 0 , len ( primary ) + len ( secondary ) )
i , j := 0 , 0
for i < len ( primary ) && j < len ( secondary ) {
2023-04-09 00:08:40 -07:00
switch {
case primary [ i ] . Name < secondary [ j ] . Name :
2019-08-19 13:16:10 -07:00
result = append ( result , primary [ i ] )
i ++
2023-04-09 00:08:40 -07:00
case primary [ i ] . Name > secondary [ j ] . Name :
2019-08-19 13:16:10 -07:00
result = append ( result , secondary [ j ] )
j ++
2023-04-09 00:08:40 -07:00
default :
2019-08-19 13:16:10 -07:00
result = append ( result , primary [ i ] )
i ++
j ++
}
}
for ; i < len ( primary ) ; i ++ {
result = append ( result , primary [ i ] )
}
for ; j < len ( secondary ) ; j ++ {
result = append ( result , secondary [ j ] )
}
return result
}
2017-11-11 17:15:27 -08:00
type byLabel [ ] storage . Series
func ( a byLabel ) Len ( ) int { return len ( a ) }
func ( a byLabel ) Swap ( i , j int ) { a [ i ] , a [ j ] = a [ j ] , a [ i ] }
func ( a byLabel ) Less ( i , j int ) bool { return labels . Compare ( a [ i ] . Labels ( ) , a [ j ] . Labels ( ) ) < 0 }
2017-10-23 13:28:17 -07:00
// errSeriesSet implements storage.SeriesSet, just returning an error.
type errSeriesSet struct {
err error
}
2017-10-23 06:44:57 -07:00
2017-10-23 13:28:17 -07:00
func ( errSeriesSet ) Next ( ) bool {
return false
}
func ( errSeriesSet ) At ( ) storage . Series {
return nil
}
func ( e errSeriesSet ) Err ( ) error {
return e . err
}
2020-06-09 09:57:31 -07:00
func ( e errSeriesSet ) Warnings ( ) storage . Warnings { return nil }
2017-10-23 13:28:17 -07:00
// concreteSeriesSet implements storage.SeriesSet.
type concreteSeriesSet struct {
cur int
series [ ] storage . Series
}
func ( c * concreteSeriesSet ) Next ( ) bool {
c . cur ++
return c . cur - 1 < len ( c . series )
}
func ( c * concreteSeriesSet ) At ( ) storage . Series {
return c . series [ c . cur - 1 ]
}
func ( c * concreteSeriesSet ) Err ( ) error {
return nil
}
2020-06-09 09:57:31 -07:00
func ( c * concreteSeriesSet ) Warnings ( ) storage . Warnings { return nil }
2018-04-08 02:51:54 -07:00
// concreteSeries implements storage.Series.
2017-10-23 13:28:17 -07:00
type concreteSeries struct {
2023-03-27 17:02:20 -07:00
labels labels . Labels
floats [ ] prompb . Sample
histograms [ ] prompb . Histogram
2017-10-23 13:28:17 -07:00
}
func ( c * concreteSeries ) Labels ( ) labels . Labels {
2022-03-09 14:26:43 -08:00
return c . labels . Copy ( )
2017-10-23 13:28:17 -07:00
}
2022-09-20 10:16:45 -07:00
func ( c * concreteSeries ) Iterator ( it chunkenc . Iterator ) chunkenc . Iterator {
2022-09-20 11:31:28 -07:00
if csi , ok := it . ( * concreteSeriesIterator ) ; ok {
csi . reset ( c )
return csi
}
2023-03-27 17:02:20 -07:00
return newConcreteSeriesIterator ( c )
2017-10-23 13:28:17 -07:00
}
// concreteSeriesIterator implements storage.SeriesIterator.
type concreteSeriesIterator struct {
2023-03-27 17:02:20 -07:00
floatsCur int
histogramsCur int
curValType chunkenc . ValueType
series * concreteSeries
2017-10-23 13:28:17 -07:00
}
2023-03-27 17:02:20 -07:00
func newConcreteSeriesIterator ( series * concreteSeries ) chunkenc . Iterator {
2017-10-23 13:28:17 -07:00
return & concreteSeriesIterator {
2023-03-27 17:02:20 -07:00
floatsCur : - 1 ,
histogramsCur : - 1 ,
curValType : chunkenc . ValNone ,
series : series ,
2017-10-23 13:28:17 -07:00
}
}
2022-09-20 11:31:28 -07:00
func ( c * concreteSeriesIterator ) reset ( series * concreteSeries ) {
2023-03-27 17:02:20 -07:00
c . floatsCur = - 1
c . histogramsCur = - 1
c . curValType = chunkenc . ValNone
2022-09-20 11:31:28 -07:00
c . series = series
}
2017-10-23 13:28:17 -07:00
// Seek implements storage.SeriesIterator.
2021-11-28 23:54:23 -08:00
func ( c * concreteSeriesIterator ) Seek ( t int64 ) chunkenc . ValueType {
2023-03-27 17:02:20 -07:00
if c . floatsCur == - 1 {
c . floatsCur = 0
}
if c . histogramsCur == - 1 {
c . histogramsCur = 0
2021-11-28 23:54:23 -08:00
}
2023-03-27 17:02:20 -07:00
if c . floatsCur >= len ( c . series . floats ) && c . histogramsCur >= len ( c . series . histograms ) {
2021-12-18 05:12:01 -08:00
return chunkenc . ValNone
2021-12-16 03:07:07 -08:00
}
2023-03-27 17:02:20 -07:00
2021-11-28 23:54:23 -08:00
// No-op check.
2023-03-27 17:02:20 -07:00
if ( c . curValType == chunkenc . ValFloat && c . series . floats [ c . floatsCur ] . Timestamp >= t ) ||
( ( c . curValType == chunkenc . ValHistogram || c . curValType == chunkenc . ValFloatHistogram ) && c . series . histograms [ c . histogramsCur ] . Timestamp >= t ) {
return c . curValType
2021-11-28 23:54:23 -08:00
}
2023-03-27 17:02:20 -07:00
c . curValType = chunkenc . ValNone
// Binary search between current position and end for both float and histograms samples.
c . floatsCur += sort . Search ( len ( c . series . floats ) - c . floatsCur , func ( n int ) bool {
return c . series . floats [ n + c . floatsCur ] . Timestamp >= t
} )
c . histogramsCur += sort . Search ( len ( c . series . histograms ) - c . histogramsCur , func ( n int ) bool {
return c . series . histograms [ n + c . histogramsCur ] . Timestamp >= t
2017-10-23 13:28:17 -07:00
} )
2023-04-09 00:08:40 -07:00
switch {
case c . floatsCur < len ( c . series . floats ) && c . histogramsCur < len ( c . series . histograms ) :
2023-03-27 17:02:20 -07:00
// If float samples and histogram samples have overlapping timestamps prefer the float samples.
if c . series . floats [ c . floatsCur ] . Timestamp <= c . series . histograms [ c . histogramsCur ] . Timestamp {
c . curValType = chunkenc . ValFloat
} else {
c . curValType = getHistogramValType ( & c . series . histograms [ c . histogramsCur ] )
}
// When the timestamps do not overlap the cursor for the non-selected sample type has advanced too
// far; we decrement it back down here.
if c . series . floats [ c . floatsCur ] . Timestamp != c . series . histograms [ c . histogramsCur ] . Timestamp {
if c . curValType == chunkenc . ValFloat {
c . histogramsCur --
} else {
c . floatsCur --
}
}
2023-04-09 00:08:40 -07:00
case c . floatsCur < len ( c . series . floats ) :
2023-03-27 17:02:20 -07:00
c . curValType = chunkenc . ValFloat
2023-04-09 00:08:40 -07:00
case c . histogramsCur < len ( c . series . histograms ) :
2023-03-27 17:02:20 -07:00
c . curValType = getHistogramValType ( & c . series . histograms [ c . histogramsCur ] )
}
return c . curValType
}
func getHistogramValType ( h * prompb . Histogram ) chunkenc . ValueType {
2023-04-21 11:27:15 -07:00
if h . IsFloatHistogram ( ) {
return chunkenc . ValFloatHistogram
2021-11-28 23:54:23 -08:00
}
2023-04-21 11:27:15 -07:00
return chunkenc . ValHistogram
2017-10-23 13:28:17 -07:00
}
2021-11-28 23:54:23 -08:00
// At implements chunkenc.Iterator.
2017-10-23 13:28:17 -07:00
func ( c * concreteSeriesIterator ) At ( ) ( t int64 , v float64 ) {
2023-03-27 17:02:20 -07:00
if c . curValType != chunkenc . ValFloat {
panic ( "iterator is not on a float sample" )
}
s := c . series . floats [ c . floatsCur ]
2017-10-23 13:28:17 -07:00
return s . Timestamp , s . Value
}
2023-03-27 17:02:20 -07:00
// AtHistogram implements chunkenc.Iterator
2021-11-12 10:07:41 -08:00
func ( c * concreteSeriesIterator ) AtHistogram ( ) ( int64 , * histogram . Histogram ) {
2023-03-27 17:02:20 -07:00
if c . curValType != chunkenc . ValHistogram {
panic ( "iterator is not on an integer histogram sample" )
}
h := c . series . histograms [ c . histogramsCur ]
return h . Timestamp , HistogramProtoToHistogram ( h )
2021-06-29 07:38:46 -07:00
}
2023-03-27 17:02:20 -07:00
// AtFloatHistogram implements chunkenc.Iterator
2021-11-28 23:54:23 -08:00
func ( c * concreteSeriesIterator ) AtFloatHistogram ( ) ( int64 , * histogram . FloatHistogram ) {
2023-03-27 17:02:20 -07:00
switch c . curValType {
case chunkenc . ValHistogram :
fh := c . series . histograms [ c . histogramsCur ]
return fh . Timestamp , HistogramProtoToFloatHistogram ( fh )
case chunkenc . ValFloatHistogram :
fh := c . series . histograms [ c . histogramsCur ]
return fh . Timestamp , FloatHistogramProtoToFloatHistogram ( fh )
default :
panic ( "iterator is not on a histogram sample" )
}
2021-11-28 23:54:23 -08:00
}
// AtT implements chunkenc.Iterator.
func ( c * concreteSeriesIterator ) AtT ( ) int64 {
2023-03-27 17:02:20 -07:00
if c . curValType == chunkenc . ValHistogram || c . curValType == chunkenc . ValFloatHistogram {
return c . series . histograms [ c . histogramsCur ] . Timestamp
}
return c . series . floats [ c . floatsCur ] . Timestamp
2021-06-30 07:48:13 -07:00
}
2023-03-27 17:02:20 -07:00
const noTS = int64 ( math . MaxInt64 )
2021-11-28 23:54:23 -08:00
// Next implements chunkenc.Iterator.
func ( c * concreteSeriesIterator ) Next ( ) chunkenc . ValueType {
2023-03-27 17:02:20 -07:00
peekFloatTS := noTS
if c . floatsCur + 1 < len ( c . series . floats ) {
peekFloatTS = c . series . floats [ c . floatsCur + 1 ] . Timestamp
}
peekHistTS := noTS
if c . histogramsCur + 1 < len ( c . series . histograms ) {
peekHistTS = c . series . histograms [ c . histogramsCur + 1 ] . Timestamp
2021-11-28 23:54:23 -08:00
}
2023-03-27 17:02:20 -07:00
c . curValType = chunkenc . ValNone
2023-04-09 00:08:40 -07:00
switch {
case peekFloatTS < peekHistTS :
2023-03-27 17:02:20 -07:00
c . floatsCur ++
c . curValType = chunkenc . ValFloat
2023-04-09 00:08:40 -07:00
case peekHistTS < peekFloatTS :
2023-03-27 17:02:20 -07:00
c . histogramsCur ++
c . curValType = chunkenc . ValHistogram
2023-04-09 00:08:40 -07:00
case peekFloatTS == noTS && peekHistTS == noTS :
2023-03-27 17:02:20 -07:00
// This only happens when the iterator is exhausted; we set the cursors off the end to prevent
// Seek() from returning anything afterwards.
c . floatsCur = len ( c . series . floats )
c . histogramsCur = len ( c . series . histograms )
2023-04-09 00:08:40 -07:00
default :
2023-03-27 17:02:20 -07:00
// Prefer float samples to histogram samples if there's a conflict. We advance the cursor for histograms
// anyway otherwise the histogram sample will get selected on the next call to Next().
c . floatsCur ++
c . histogramsCur ++
c . curValType = chunkenc . ValFloat
}
return c . curValType
2017-10-23 13:28:17 -07:00
}
2021-11-28 23:54:23 -08:00
// Err implements chunkenc.Iterator.
2017-10-23 13:28:17 -07:00
func ( c * concreteSeriesIterator ) Err ( ) error {
return nil
}
2019-08-07 08:13:10 -07:00
// validateLabelsAndMetricName validates the label names/values and metric names returned from remote read,
// also making sure that there are no labels with duplicate names
2022-03-09 14:26:43 -08:00
func validateLabelsAndMetricName ( ls [ ] prompb . Label ) error {
2019-08-07 08:13:10 -07:00
for i , l := range ls {
2017-10-23 13:28:17 -07:00
if l . Name == labels . MetricName && ! model . IsValidMetricName ( model . LabelValue ( l . Value ) ) {
2022-07-01 09:59:50 -07:00
return fmt . Errorf ( "invalid metric name: %v" , l . Value )
2017-10-23 13:28:17 -07:00
}
if ! model . LabelName ( l . Name ) . IsValid ( ) {
2022-07-01 09:59:50 -07:00
return fmt . Errorf ( "invalid label name: %v" , l . Name )
2017-10-23 13:28:17 -07:00
}
if ! model . LabelValue ( l . Value ) . IsValid ( ) {
2022-07-01 09:59:50 -07:00
return fmt . Errorf ( "invalid label value: %v" , l . Value )
2017-10-23 13:28:17 -07:00
}
2019-08-07 08:13:10 -07:00
if i > 0 && l . Name == ls [ i - 1 ] . Name {
2022-07-01 09:59:50 -07:00
return fmt . Errorf ( "duplicate label with name: %v" , l . Name )
2019-08-07 08:13:10 -07:00
}
2017-10-23 13:28:17 -07:00
}
return nil
2017-10-23 06:44:57 -07:00
}
func toLabelMatchers ( matchers [ ] * labels . Matcher ) ( [ ] * prompb . LabelMatcher , error ) {
pbMatchers := make ( [ ] * prompb . LabelMatcher , 0 , len ( matchers ) )
for _ , m := range matchers {
var mType prompb . LabelMatcher_Type
switch m . Type {
case labels . MatchEqual :
mType = prompb . LabelMatcher_EQ
case labels . MatchNotEqual :
mType = prompb . LabelMatcher_NEQ
case labels . MatchRegexp :
mType = prompb . LabelMatcher_RE
case labels . MatchNotRegexp :
mType = prompb . LabelMatcher_NRE
default :
2019-03-25 16:01:12 -07:00
return nil , errors . New ( "invalid matcher type" )
2017-10-23 06:44:57 -07:00
}
pbMatchers = append ( pbMatchers , & prompb . LabelMatcher {
Type : mType ,
Name : m . Name ,
Value : m . Value ,
} )
}
return pbMatchers , nil
}
2019-08-19 13:16:10 -07:00
// FromLabelMatchers parses protobuf label matchers to Prometheus label matchers.
func FromLabelMatchers ( matchers [ ] * prompb . LabelMatcher ) ( [ ] * labels . Matcher , error ) {
2017-10-23 06:44:57 -07:00
result := make ( [ ] * labels . Matcher , 0 , len ( matchers ) )
for _ , matcher := range matchers {
var mtype labels . MatchType
switch matcher . Type {
case prompb . LabelMatcher_EQ :
mtype = labels . MatchEqual
case prompb . LabelMatcher_NEQ :
mtype = labels . MatchNotEqual
case prompb . LabelMatcher_RE :
mtype = labels . MatchRegexp
case prompb . LabelMatcher_NRE :
mtype = labels . MatchNotRegexp
default :
2019-03-25 16:01:12 -07:00
return nil , errors . New ( "invalid matcher type" )
2017-10-23 06:44:57 -07:00
}
matcher , err := labels . NewMatcher ( mtype , matcher . Name , matcher . Value )
if err != nil {
return nil , err
}
result = append ( result , matcher )
}
return result , nil
}
2021-09-21 13:53:27 -07:00
func exemplarProtoToExemplar ( ep prompb . Exemplar ) exemplar . Exemplar {
timestamp := ep . Timestamp
return exemplar . Exemplar {
Labels : labelProtosToLabels ( ep . Labels ) ,
Value : ep . Value ,
Ts : timestamp ,
HasTs : timestamp != 0 ,
}
}
2022-07-13 04:02:45 -07:00
// HistogramProtoToHistogram extracts a (normal integer) Histogram from the
2023-04-21 11:27:15 -07:00
// provided proto message. The caller has to make sure that the proto message
// represents an integer histogram and not a float histogram, or it panics.
2022-07-13 04:02:45 -07:00
func HistogramProtoToHistogram ( hp prompb . Histogram ) * histogram . Histogram {
2023-04-21 11:27:15 -07:00
if hp . IsFloatHistogram ( ) {
2023-04-21 11:27:15 -07:00
panic ( "HistogramProtoToHistogram called with a float histogram" )
2023-04-21 11:27:15 -07:00
}
2022-07-13 04:02:45 -07:00
return & histogram . Histogram {
2023-01-24 03:56:30 -08:00
CounterResetHint : histogram . CounterResetHint ( hp . ResetHint ) ,
Schema : hp . Schema ,
ZeroThreshold : hp . ZeroThreshold ,
ZeroCount : hp . GetZeroCountInt ( ) ,
Count : hp . GetCountInt ( ) ,
Sum : hp . Sum ,
PositiveSpans : spansProtoToSpans ( hp . GetPositiveSpans ( ) ) ,
PositiveBuckets : hp . GetPositiveDeltas ( ) ,
NegativeSpans : spansProtoToSpans ( hp . GetNegativeSpans ( ) ) ,
NegativeBuckets : hp . GetNegativeDeltas ( ) ,
2022-07-14 06:13:12 -07:00
}
}
2023-03-27 17:02:20 -07:00
// FloatHistogramProtoToFloatHistogram extracts a float Histogram from the
2023-04-21 11:27:15 -07:00
// provided proto message to a Float Histogram. The caller has to make sure that
// the proto message represents a float histogram and not an integer histogram,
// or it panics.
2023-03-27 17:02:20 -07:00
func FloatHistogramProtoToFloatHistogram ( hp prompb . Histogram ) * histogram . FloatHistogram {
2023-04-21 11:27:15 -07:00
if ! hp . IsFloatHistogram ( ) {
2023-04-21 11:27:15 -07:00
panic ( "FloatHistogramProtoToFloatHistogram called with an integer histogram" )
2023-04-21 11:27:15 -07:00
}
2023-01-13 03:09:20 -08:00
return & histogram . FloatHistogram {
2023-01-24 03:56:30 -08:00
CounterResetHint : histogram . CounterResetHint ( hp . ResetHint ) ,
Schema : hp . Schema ,
ZeroThreshold : hp . ZeroThreshold ,
ZeroCount : hp . GetZeroCountFloat ( ) ,
Count : hp . GetCountFloat ( ) ,
Sum : hp . Sum ,
PositiveSpans : spansProtoToSpans ( hp . GetPositiveSpans ( ) ) ,
PositiveBuckets : hp . GetPositiveCounts ( ) ,
NegativeSpans : spansProtoToSpans ( hp . GetNegativeSpans ( ) ) ,
NegativeBuckets : hp . GetNegativeCounts ( ) ,
2023-01-13 03:09:20 -08:00
}
}
2023-03-27 17:02:20 -07:00
// HistogramProtoToFloatHistogram extracts and converts a (normal integer) histogram from the provided proto message
2023-04-21 11:27:15 -07:00
// to a float histogram. The caller has to make sure that the proto message represents an integer histogram and not a
// float histogram, or it panics.
2023-03-27 17:02:20 -07:00
func HistogramProtoToFloatHistogram ( hp prompb . Histogram ) * histogram . FloatHistogram {
2023-04-21 11:27:15 -07:00
if hp . IsFloatHistogram ( ) {
2023-04-21 11:27:15 -07:00
panic ( "HistogramProtoToFloatHistogram called with a float histogram" )
2023-04-21 11:27:15 -07:00
}
2023-03-27 17:02:20 -07:00
return & histogram . FloatHistogram {
CounterResetHint : histogram . CounterResetHint ( hp . ResetHint ) ,
Schema : hp . Schema ,
ZeroThreshold : hp . ZeroThreshold ,
ZeroCount : float64 ( hp . GetZeroCountInt ( ) ) ,
Count : float64 ( hp . GetCountInt ( ) ) ,
Sum : hp . Sum ,
PositiveSpans : spansProtoToSpans ( hp . GetPositiveSpans ( ) ) ,
PositiveBuckets : deltasToCounts ( hp . GetPositiveDeltas ( ) ) ,
NegativeSpans : spansProtoToSpans ( hp . GetNegativeSpans ( ) ) ,
NegativeBuckets : deltasToCounts ( hp . GetNegativeDeltas ( ) ) ,
}
}
2023-02-02 18:46:33 -08:00
func spansProtoToSpans ( s [ ] prompb . BucketSpan ) [ ] histogram . Span {
2022-07-14 06:13:12 -07:00
spans := make ( [ ] histogram . Span , len ( s ) )
for i := 0 ; i < len ( s ) ; i ++ {
spans [ i ] = histogram . Span { Offset : s [ i ] . Offset , Length : s [ i ] . Length }
}
return spans
}
2023-03-27 17:02:20 -07:00
func deltasToCounts ( deltas [ ] int64 ) [ ] float64 {
counts := make ( [ ] float64 , len ( deltas ) )
var cur float64
for i , d := range deltas {
cur += float64 ( d )
counts [ i ] = cur
}
return counts
}
2022-07-21 07:12:50 -07:00
func HistogramToHistogramProto ( timestamp int64 , h * histogram . Histogram ) prompb . Histogram {
2022-07-14 06:13:12 -07:00
return prompb . Histogram {
2022-07-13 04:02:45 -07:00
Count : & prompb . Histogram_CountInt { CountInt : h . Count } ,
Sum : h . Sum ,
Schema : h . Schema ,
ZeroThreshold : h . ZeroThreshold ,
ZeroCount : & prompb . Histogram_ZeroCountInt { ZeroCountInt : h . ZeroCount } ,
NegativeSpans : spansToSpansProto ( h . NegativeSpans ) ,
NegativeDeltas : h . NegativeBuckets ,
PositiveSpans : spansToSpansProto ( h . PositiveSpans ) ,
PositiveDeltas : h . PositiveBuckets ,
2023-01-24 03:56:30 -08:00
ResetHint : prompb . Histogram_ResetHint ( h . CounterResetHint ) ,
2023-01-13 03:09:20 -08:00
Timestamp : timestamp ,
}
}
func FloatHistogramToHistogramProto ( timestamp int64 , fh * histogram . FloatHistogram ) prompb . Histogram {
return prompb . Histogram {
Count : & prompb . Histogram_CountFloat { CountFloat : fh . Count } ,
Sum : fh . Sum ,
Schema : fh . Schema ,
ZeroThreshold : fh . ZeroThreshold ,
ZeroCount : & prompb . Histogram_ZeroCountFloat { ZeroCountFloat : fh . ZeroCount } ,
NegativeSpans : spansToSpansProto ( fh . NegativeSpans ) ,
NegativeCounts : fh . NegativeBuckets ,
PositiveSpans : spansToSpansProto ( fh . PositiveSpans ) ,
PositiveCounts : fh . PositiveBuckets ,
2023-01-24 03:56:30 -08:00
ResetHint : prompb . Histogram_ResetHint ( fh . CounterResetHint ) ,
2022-07-13 04:02:45 -07:00
Timestamp : timestamp ,
}
}
2023-02-02 18:46:33 -08:00
func spansToSpansProto ( s [ ] histogram . Span ) [ ] prompb . BucketSpan {
spans := make ( [ ] prompb . BucketSpan , len ( s ) )
2022-07-14 06:13:12 -07:00
for i := 0 ; i < len ( s ) ; i ++ {
2023-02-02 18:46:33 -08:00
spans [ i ] = prompb . BucketSpan { Offset : s [ i ] . Offset , Length : s [ i ] . Length }
2022-07-14 06:13:12 -07:00
}
return spans
}
2017-10-23 08:56:47 -07:00
// LabelProtosToMetric unpack a []*prompb.Label to a model.Metric
func LabelProtosToMetric ( labelPairs [ ] * prompb . Label ) model . Metric {
2017-10-23 06:44:57 -07:00
metric := make ( model . Metric , len ( labelPairs ) )
for _ , l := range labelPairs {
metric [ model . LabelName ( l . Name ) ] = model . LabelValue ( l . Value )
}
return metric
}
2017-10-23 08:56:47 -07:00
2019-01-15 11:13:39 -08:00
func labelProtosToLabels ( labelPairs [ ] prompb . Label ) labels . Labels {
2022-03-09 14:26:43 -08:00
b := labels . ScratchBuilder { }
2017-10-23 08:56:47 -07:00
for _ , l := range labelPairs {
2022-03-09 14:26:43 -08:00
b . Add ( l . Name , l . Value )
2017-10-23 08:56:47 -07:00
}
2022-03-09 14:26:43 -08:00
b . Sort ( )
return b . Labels ( )
2017-10-23 08:56:47 -07:00
}
2019-08-12 09:22:02 -07:00
// labelsToLabelsProto transforms labels into prompb labels. The buffer slice
// will be used to avoid allocations if it is big enough to store the labels.
2022-03-09 14:26:43 -08:00
func labelsToLabelsProto ( lbls labels . Labels , buf [ ] prompb . Label ) [ ] prompb . Label {
2019-08-12 09:22:02 -07:00
result := buf [ : 0 ]
2022-03-09 14:26:43 -08:00
lbls . Range ( func ( l labels . Label ) {
2019-01-15 11:13:39 -08:00
result = append ( result , prompb . Label {
2019-08-07 12:39:07 -07:00
Name : l . Name ,
Value : l . Value ,
2017-10-23 13:28:17 -07:00
} )
2022-03-09 14:26:43 -08:00
} )
2017-10-23 13:28:17 -07:00
return result
}
2020-11-19 07:23:03 -08:00
// metricTypeToMetricTypeProto transforms a Prometheus metricType into prompb metricType. Since the former is a string we need to transform it to an enum.
func metricTypeToMetricTypeProto ( t textparse . MetricType ) prompb . MetricMetadata_MetricType {
mt := strings . ToUpper ( string ( t ) )
v , ok := prompb . MetricMetadata_MetricType_value [ mt ]
if ! ok {
return prompb . MetricMetadata_UNKNOWN
}
return prompb . MetricMetadata_MetricType ( v )
}
2021-01-30 03:04:48 -08:00
// DecodeWriteRequest from an io.Reader into a prompb.WriteRequest, handling
// snappy decompression.
func DecodeWriteRequest ( r io . Reader ) ( * prompb . WriteRequest , error ) {
2022-04-27 02:24:36 -07:00
compressed , err := io . ReadAll ( r )
2021-01-30 03:04:48 -08:00
if err != nil {
return nil , err
}
reqBuf , err := snappy . Decode ( nil , compressed )
if err != nil {
return nil , err
}
var req prompb . WriteRequest
if err := proto . Unmarshal ( reqBuf , & req ) ; err != nil {
return nil , err
}
return & req , nil
}