2025-12-22 04:38:48 -05:00
// Copyright The Prometheus Authors
2016-02-17 13:33:17 -05: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.
2018-02-01 04:55:07 -05:00
package scrape
2016-02-17 13:33:17 -05:00
2016-02-22 10:46:55 -05:00
import (
2017-02-22 07:00:51 -05:00
"bufio"
2017-01-15 11:33:07 -05:00
"bytes"
2017-10-25 00:21:42 -04:00
"context"
2023-11-01 15:06:46 -04:00
"errors"
2016-02-28 13:21:50 -05:00
"fmt"
"io"
2024-09-09 21:41:53 -04:00
"log/slog"
2017-04-13 13:07:23 -04:00
"math"
2016-02-28 13:21:50 -05:00
"net/http"
2025-07-15 03:37:24 -04:00
"net/http/httptrace"
2020-01-22 07:13:47 -05:00
"reflect"
2024-01-15 11:24:46 -05:00
"slices"
2021-06-18 03:38:12 -04:00
"strconv"
2023-10-10 06:16:55 -04:00
"strings"
2016-02-22 10:46:55 -05:00
"sync"
"time"
2025-01-15 06:33:42 -05:00
"unsafe"
2016-02-17 13:33:17 -05:00
2022-05-31 05:46:49 -04:00
"github.com/klauspost/compress/gzip"
2018-04-25 13:19:06 -04:00
config_util "github.com/prometheus/common/config"
2017-09-08 08:34:45 -04:00
"github.com/prometheus/common/model"
2024-09-09 21:41:53 -04:00
"github.com/prometheus/common/promslog"
2017-02-28 08:59:33 -05:00
"github.com/prometheus/common/version"
2025-07-15 03:37:24 -04:00
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
2025-10-30 06:58:31 -04:00
"go.uber.org/atomic"
2016-02-17 13:33:17 -05:00
2016-02-23 05:56:09 -05:00
"github.com/prometheus/prometheus/config"
Refactor SD configuration to remove `config` dependency (#3629)
* refactor: move targetGroup struct and CheckOverflow() to their own package
* refactor: move auth and security related structs to a utility package, fix import error in utility package
* refactor: Azure SD, remove SD struct from config
* refactor: DNS SD, remove SD struct from config into dns package
* refactor: ec2 SD, move SD struct from config into the ec2 package
* refactor: file SD, move SD struct from config to file discovery package
* refactor: gce, move SD struct from config to gce discovery package
* refactor: move HTTPClientConfig and URL into util/config, fix import error in httputil
* refactor: consul, move SD struct from config into consul discovery package
* refactor: marathon, move SD struct from config into marathon discovery package
* refactor: triton, move SD struct from config to triton discovery package, fix test
* refactor: zookeeper, move SD structs from config to zookeeper discovery package
* refactor: openstack, remove SD struct from config, move into openstack discovery package
* refactor: kubernetes, move SD struct from config into kubernetes discovery package
* refactor: notifier, use targetgroup package instead of config
* refactor: tests for file, marathon, triton SD - use targetgroup package instead of config.TargetGroup
* refactor: retrieval, use targetgroup package instead of config.TargetGroup
* refactor: storage, use config util package
* refactor: discovery manager, use targetgroup package instead of config.TargetGroup
* refactor: use HTTPClient and TLS config from configUtil instead of config
* refactor: tests, use targetgroup package instead of config.TargetGroup
* refactor: fix tagetgroup.Group pointers that were removed by mistake
* refactor: openstack, kubernetes: drop prefixes
* refactor: remove import aliases forced due to vscode bug
* refactor: move main SD struct out of config into discovery/config
* refactor: rename configUtil to config_util
* refactor: rename yamlUtil to yaml_config
* refactor: kubernetes, remove prefixes
* refactor: move the TargetGroup package to discovery/
* refactor: fix order of imports
2017-12-29 15:01:34 -05:00
"github.com/prometheus/prometheus/discovery/targetgroup"
2021-11-08 09:23:17 -05: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 09:57:07 -04:00
"github.com/prometheus/prometheus/model/histogram"
2021-11-08 09:23:17 -05:00
"github.com/prometheus/prometheus/model/labels"
2022-08-31 09:50:05 -04:00
"github.com/prometheus/prometheus/model/metadata"
2021-11-08 09:23:17 -05:00
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/model/textparse"
"github.com/prometheus/prometheus/model/timestamp"
"github.com/prometheus/prometheus/model/value"
2016-02-22 10:46:55 -05:00
"github.com/prometheus/prometheus/storage"
2024-09-09 21:41:53 -04:00
"github.com/prometheus/prometheus/util/logging"
2025-08-18 04:09:00 -04:00
"github.com/prometheus/prometheus/util/namevalidationutil"
2021-11-08 09:23:17 -05:00
"github.com/prometheus/prometheus/util/pool"
2016-02-22 10:46:55 -05:00
)
2016-02-17 13:33:17 -05:00
2025-12-22 04:38:48 -05:00
var aOptionRejectEarlyOOO = storage . AppendOptions { DiscardOutOfOrder : true }
2021-09-08 07:57:33 -04:00
// ScrapeTimestampTolerance is the tolerance for scrape appends timestamps
// alignment, to enable better compression at the TSDB level.
2020-09-25 09:44:47 -04:00
// See https://github.com/prometheus/prometheus/issues/7846
2021-09-08 07:57:33 -04:00
var ScrapeTimestampTolerance = 2 * time . Millisecond
2020-10-07 12:25:52 -04:00
2020-10-07 15:44:36 -04:00
// AlignScrapeTimestamps enables the tolerance for scrape appends timestamps described above.
2020-10-07 12:25:52 -04:00
var AlignScrapeTimestamps = true
2020-09-25 09:44:47 -04:00
2025-12-22 04:38:48 -05:00
var errNameLabelMandatory = fmt . Errorf ( "missing metric name (%s label)" , model . MetricNameLabel )
2020-03-02 02:18:05 -05:00
2024-11-23 23:30:23 -05:00
var _ FailureLogger = ( * logging . JSONFileLogger ) ( nil )
// FailureLogger is an interface that can be used to log all failed
// scrapes.
type FailureLogger interface {
slog . Handler
io . Closer
}
2016-02-22 10:46:55 -05:00
// scrapePool manages scrapes for sets of targets.
type scrapePool struct {
2026-01-21 03:21:56 -05:00
appendable storage . Appendable
appendableV2 storage . AppendableV2
logger * slog . Logger
ctx context . Context
cancel context . CancelFunc
options * Options
2016-02-17 13:33:17 -05:00
2020-11-12 11:06:25 -05:00
// mtx must not be taken after targetMtx.
2021-07-27 06:48:55 -04:00
mtx sync . Mutex
config * config . ScrapeConfig
client * http . Client
loops map [ uint64 ] loop
2020-10-26 10:46:20 -04:00
2023-11-24 14:46:26 -05:00
symbolTable * labels . SymbolTable
lastSymbolTableCheck time . Time
initialSymbolTableLen int
2023-11-23 14:02:37 -05:00
2020-11-12 11:06:25 -05:00
targetMtx sync . Mutex
// activeTargets and loops must always be synchronized to have the same
2016-02-28 13:56:18 -05:00
// set of hashes.
2023-08-14 10:39:25 -04:00
activeTargets map [ uint64 ] * Target
droppedTargets [ ] * Target // Subject to KeepDroppedTargets limit.
droppedTargetsCount int // Count of all dropped targets.
2016-02-28 03:51:02 -05:00
2025-12-22 04:38:48 -05:00
// newLoop injection for testing purposes.
injectTestNewLoop func ( scrapeLoopOptions ) loop
2022-07-20 07:35:47 -04:00
2025-12-22 04:38:48 -05:00
metrics * scrapeMetrics
buffers * pool . Pool
offsetSeed uint64
2024-08-26 05:41:56 -04:00
2024-11-23 23:30:23 -05:00
scrapeFailureLogger FailureLogger
2024-08-26 05:41:56 -04:00
scrapeFailureLoggerMtx sync . RWMutex
2019-03-12 06:26:18 -04:00
}
2021-05-06 04:56:21 -04:00
type labelLimits struct {
labelLimit int
labelNameLengthLimit int
labelValueLengthLimit int
}
2017-09-08 08:34:45 -04:00
const maxAheadTime = 10 * time . Minute
2023-10-03 16:09:25 -04:00
// returning an empty label set is interpreted as "drop".
2017-09-08 08:34:45 -04:00
type labelsMutator func ( labels . Labels ) labels . Labels
2025-12-22 04:38:48 -05:00
// scrapeLoopAppendAdapter allows support for multiple storage.Appender versions.
type scrapeLoopAppendAdapter interface {
Commit ( ) error
Rollback ( ) error
addReportSample ( s reportSample , t int64 , v float64 , b * labels . Builder , rejectOOO bool ) error
append ( b [ ] byte , contentType string , ts time . Time ) ( total , added , seriesAdded int , err error )
}
func newScrapePool (
cfg * config . ScrapeConfig ,
appendable storage . Appendable ,
2026-01-21 03:21:56 -05:00
appendableV2 storage . AppendableV2 ,
2025-12-22 04:38:48 -05:00
offsetSeed uint64 ,
logger * slog . Logger ,
buffers * pool . Pool ,
options * Options ,
metrics * scrapeMetrics ,
) ( * scrapePool , error ) {
2017-09-15 13:45:27 -04:00
if logger == nil {
2024-09-09 21:41:53 -04:00
logger = promslog . NewNopLogger ( )
2017-09-15 13:45:27 -04:00
}
2025-12-22 04:38:48 -05:00
if buffers == nil {
buffers = pool . New ( 1e3 , 1e6 , 3 , func ( sz int ) any { return make ( [ ] byte , 0 , sz ) } )
}
2017-09-15 13:45:27 -04:00
2025-07-15 03:37:24 -04:00
client , err := newScrapeClient ( cfg . HTTPClientConfig , cfg . JobName , options . HTTPClientOptions ... )
2016-02-28 13:21:50 -05:00
if err != nil {
2025-07-15 03:37:24 -04:00
return nil , err
2016-02-28 13:21:50 -05:00
}
2017-05-26 04:44:48 -04:00
2025-12-22 04:38:48 -05:00
// Validate scheme so we don't need to do it later.
// We also do it on scrapePool.reload(...)
// TODO(bwplotka): Can we move it to scrape config validation?
2025-08-18 04:09:00 -04:00
if err := namevalidationutil . CheckNameValidationScheme ( cfg . MetricNameValidationScheme ) ; err != nil {
return nil , errors . New ( "newScrapePool: MetricNameValidationScheme must be set in scrape configuration" )
}
2025-12-22 04:38:48 -05:00
if _ , err = config . ToEscapingScheme ( cfg . MetricNameEscapingScheme , cfg . MetricNameValidationScheme ) ; err != nil {
2025-03-26 18:27:28 -04:00
return nil , fmt . Errorf ( "invalid metric name escaping scheme, %w" , err )
}
2025-12-22 04:38:48 -05:00
symbols := labels . NewSymbolTable ( )
2017-12-03 12:14:08 -05:00
ctx , cancel := context . WithCancel ( context . Background ( ) )
2017-09-08 08:34:45 -04:00
sp := & scrapePool {
2025-12-22 04:38:48 -05:00
appendable : appendable ,
2026-01-21 03:21:56 -05:00
appendableV2 : appendableV2 ,
2025-12-22 04:38:48 -05:00
logger : logger ,
ctx : ctx ,
2023-11-24 14:46:26 -05:00
cancel : cancel ,
2025-12-22 04:38:48 -05:00
options : options ,
2023-11-24 14:46:26 -05:00
config : cfg ,
client : client ,
loops : map [ uint64 ] loop { } ,
2025-12-22 04:38:48 -05:00
symbolTable : symbols ,
2023-11-24 14:46:26 -05:00
lastSymbolTableCheck : time . Now ( ) ,
2025-12-22 04:38:48 -05:00
activeTargets : map [ uint64 ] * Target { } ,
2023-11-24 14:46:26 -05:00
metrics : metrics ,
2025-12-22 04:38:48 -05:00
buffers : buffers ,
offsetSeed : offsetSeed ,
2016-02-22 10:46:55 -05:00
}
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolTargetLimit . WithLabelValues ( sp . config . JobName ) . Set ( float64 ( sp . config . TargetLimit ) )
2019-02-13 08:24:22 -05:00
return sp , nil
2016-02-22 10:46:55 -05:00
}
2016-02-17 13:33:17 -05:00
2025-12-22 04:38:48 -05:00
func ( sp * scrapePool ) newLoop ( opts scrapeLoopOptions ) loop {
if sp . injectTestNewLoop != nil {
return sp . injectTestNewLoop ( opts )
}
return newScrapeLoop ( opts )
}
2018-09-26 05:20:56 -04:00
func ( sp * scrapePool ) ActiveTargets ( ) [ ] * Target {
2020-10-26 10:46:20 -04:00
sp . targetMtx . Lock ( )
defer sp . targetMtx . Unlock ( )
2018-09-26 05:20:56 -04:00
var tActive [ ] * Target
for _ , t := range sp . activeTargets {
tActive = append ( tActive , t )
}
return tActive
}
2023-08-14 10:39:25 -04:00
// Return dropped targets, subject to KeepDroppedTargets limit.
2018-09-26 05:20:56 -04:00
func ( sp * scrapePool ) DroppedTargets ( ) [ ] * Target {
2020-10-26 10:46:20 -04:00
sp . targetMtx . Lock ( )
defer sp . targetMtx . Unlock ( )
2018-09-26 05:20:56 -04:00
return sp . droppedTargets
}
2023-08-14 10:39:25 -04:00
func ( sp * scrapePool ) DroppedTargetsCount ( ) int {
sp . targetMtx . Lock ( )
defer sp . targetMtx . Unlock ( )
return sp . droppedTargetsCount
}
2024-11-23 23:30:23 -05:00
func ( sp * scrapePool ) SetScrapeFailureLogger ( l FailureLogger ) {
2024-08-26 05:41:56 -04:00
sp . scrapeFailureLoggerMtx . Lock ( )
defer sp . scrapeFailureLoggerMtx . Unlock ( )
if l != nil {
2024-11-23 23:30:23 -05:00
l = slog . New ( l ) . With ( "job_name" , sp . config . JobName ) . Handler ( ) . ( FailureLogger )
2024-08-26 05:41:56 -04:00
}
sp . scrapeFailureLogger = l
sp . targetMtx . Lock ( )
defer sp . targetMtx . Unlock ( )
for _ , s := range sp . loops {
s . setScrapeFailureLogger ( sp . scrapeFailureLogger )
}
}
2024-11-23 23:30:23 -05:00
func ( sp * scrapePool ) getScrapeFailureLogger ( ) FailureLogger {
2024-08-26 05:41:56 -04:00
sp . scrapeFailureLoggerMtx . RLock ( )
defer sp . scrapeFailureLoggerMtx . RUnlock ( )
return sp . scrapeFailureLogger
}
2016-02-23 08:37:25 -05:00
// stop terminates all scrape loops and returns after they all terminated.
2016-02-22 10:46:55 -05:00
func ( sp * scrapePool ) stop ( ) {
2020-11-12 11:06:25 -05:00
sp . mtx . Lock ( )
defer sp . mtx . Unlock ( )
2017-12-03 12:14:08 -05:00
sp . cancel ( )
2016-02-22 10:46:55 -05:00
var wg sync . WaitGroup
2016-02-17 13:33:17 -05:00
2020-10-26 10:46:20 -04:00
sp . targetMtx . Lock ( )
2016-02-17 13:33:17 -05:00
2016-02-28 03:51:02 -05:00
for fp , l := range sp . loops {
2016-02-23 08:37:25 -05:00
wg . Add ( 1 )
2016-02-17 13:33:17 -05:00
2016-02-23 08:37:25 -05:00
go func ( l loop ) {
l . stop ( )
wg . Done ( )
} ( l )
2016-02-28 03:51:02 -05:00
delete ( sp . loops , fp )
2018-09-26 05:20:56 -04:00
delete ( sp . activeTargets , fp )
2016-02-22 10:46:55 -05:00
}
2020-10-26 10:46:20 -04:00
sp . targetMtx . Unlock ( )
2016-02-22 10:46:55 -05:00
wg . Wait ( )
2019-04-10 08:20:00 -04:00
sp . client . CloseIdleConnections ( )
2020-07-30 08:20:24 -04:00
if sp . config != nil {
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolSyncsCounter . DeleteLabelValues ( sp . config . JobName )
sp . metrics . targetScrapePoolTargetLimit . DeleteLabelValues ( sp . config . JobName )
sp . metrics . targetScrapePoolTargetsAdded . DeleteLabelValues ( sp . config . JobName )
2024-04-02 09:56:19 -04:00
sp . metrics . targetScrapePoolSymbolTableItems . DeleteLabelValues ( sp . config . JobName )
2023-09-22 12:47:44 -04:00
sp . metrics . targetSyncIntervalLength . DeleteLabelValues ( sp . config . JobName )
2025-11-27 12:45:35 -05:00
sp . metrics . targetSyncIntervalLengthHistogram . DeleteLabelValues ( sp . config . JobName )
2023-09-22 12:47:44 -04:00
sp . metrics . targetSyncFailed . DeleteLabelValues ( sp . config . JobName )
2020-07-30 08:20:24 -04:00
}
2016-02-22 10:46:55 -05:00
}
2016-02-23 08:37:25 -05:00
// reload the scrape pool with the given scrape configuration. The target state is preserved
// but all scrape loops are restarted with the new scrape configuration.
2017-05-10 11:59:02 -04:00
// This method returns after all scrape loops that were stopped have stopped scraping.
2019-02-13 08:24:22 -05:00
func ( sp * scrapePool ) reload ( cfg * config . ScrapeConfig ) error {
2020-11-12 11:06:25 -05:00
sp . mtx . Lock ( )
defer sp . mtx . Unlock ( )
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolReloads . Inc ( )
2016-03-09 10:33:10 -05:00
start := time . Now ( )
2016-11-22 06:48:30 -05:00
2025-12-22 04:38:48 -05:00
client , err := newScrapeClient ( cfg . HTTPClientConfig , cfg . JobName , sp . options . HTTPClientOptions ... )
2016-02-28 13:21:50 -05:00
if err != nil {
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolReloadsFailed . Inc ( )
2025-07-15 03:37:24 -04:00
return err
2016-02-28 13:21:50 -05:00
}
2020-01-22 07:13:47 -05:00
reuseCache := reusableCache ( sp . config , cfg )
2016-02-23 07:34:24 -05:00
sp . config = cfg
2019-04-10 08:20:00 -04:00
oldClient := sp . client
2016-02-28 13:21:50 -05:00
sp . client = client
2025-12-22 04:38:48 -05:00
// Validate scheme so we don't need to do it later.
2025-08-18 04:09:00 -04:00
if err := namevalidationutil . CheckNameValidationScheme ( cfg . MetricNameValidationScheme ) ; err != nil {
return errors . New ( "scrapePool.reload: MetricNameValidationScheme must be set in scrape configuration" )
}
2025-12-22 04:38:48 -05:00
if _ , err = config . ToEscapingScheme ( cfg . MetricNameEscapingScheme , cfg . MetricNameValidationScheme ) ; err != nil {
return fmt . Errorf ( "scrapePool.reload: invalid metric name escaping scheme, %w" , err )
2025-03-26 18:27:28 -04:00
}
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolTargetLimit . WithLabelValues ( sp . config . JobName ) . Set ( float64 ( sp . config . TargetLimit ) )
2020-07-30 08:20:24 -04:00
2024-04-09 13:43:49 -04:00
sp . restartLoops ( reuseCache )
oldClient . CloseIdleConnections ( )
sp . metrics . targetReloadIntervalLength . WithLabelValues ( time . Duration ( sp . config . ScrapeInterval ) . String ( ) ) . Observe (
time . Since ( start ) . Seconds ( ) ,
)
return nil
}
func ( sp * scrapePool ) restartLoops ( reuseCache bool ) {
2025-12-22 04:38:48 -05:00
var wg sync . WaitGroup
2020-10-26 10:46:20 -04:00
sp . targetMtx . Lock ( )
2020-07-30 08:20:24 -04:00
forcedErr := sp . refreshTargetLimitErr ( )
2016-02-23 08:37:25 -05:00
for fp , oldLoop := range sp . loops {
2020-01-22 07:13:47 -05:00
var cache * scrapeCache
if oc := oldLoop . getCache ( ) ; reuseCache && oc != nil {
2020-03-20 12:43:26 -04:00
oldLoop . disableEndOfRunStalenessMarkers ( )
2020-01-22 07:13:47 -05:00
cache = oc
} else {
2023-09-22 12:47:44 -04:00
cache = newScrapeCache ( sp . metrics )
2020-01-22 07:13:47 -05:00
}
2021-08-31 11:37:32 -04:00
2022-06-28 05:58:52 -04:00
t := sp . activeTargets [ fp ]
2025-12-22 04:38:48 -05:00
targetInterval , targetTimeout , err := t . intervalAndTimeout (
time . Duration ( sp . config . ScrapeInterval ) ,
time . Duration ( sp . config . ScrapeTimeout ) ,
)
escapingScheme , _ := config . ToEscapingScheme ( sp . config . MetricNameEscapingScheme , sp . config . MetricNameValidationScheme )
newLoop := sp . newLoop ( scrapeLoopOptions {
target : t ,
scraper : & targetScraper {
2023-11-20 07:02:53 -05:00
Target : t ,
client : sp . client ,
2024-04-10 10:39:17 -04:00
timeout : targetTimeout ,
2025-12-22 04:38:48 -05:00
bodySizeLimit : int64 ( sp . config . BodySizeLimit ) ,
acceptHeader : acceptHeader ( sp . config . ScrapeProtocols , escapingScheme ) ,
acceptEncodingHeader : acceptEncodingHeader ( sp . config . EnableCompression ) ,
2024-12-02 09:08:37 -05:00
metrics : sp . metrics ,
2025-12-22 04:38:48 -05:00
} ,
cache : cache ,
interval : targetInterval ,
timeout : targetTimeout ,
sp : sp ,
} )
2022-06-28 05:58:52 -04:00
if err != nil {
newLoop . setForcedError ( err )
}
2016-02-23 08:37:25 -05:00
wg . Add ( 1 )
2016-02-23 07:34:24 -05:00
2016-02-23 08:37:25 -05:00
go func ( oldLoop , newLoop loop ) {
oldLoop . stop ( )
wg . Done ( )
2016-02-23 07:34:24 -05:00
2020-07-30 08:20:24 -04:00
newLoop . setForcedError ( forcedErr )
2024-08-26 05:41:56 -04:00
newLoop . setScrapeFailureLogger ( sp . getScrapeFailureLogger ( ) )
2021-08-31 11:37:32 -04:00
newLoop . run ( nil )
2016-02-23 08:37:25 -05:00
} ( oldLoop , newLoop )
sp . loops [ fp ] = newLoop
2016-02-23 07:34:24 -05:00
}
2020-10-26 10:46:20 -04:00
sp . targetMtx . Unlock ( )
2016-02-23 07:34:24 -05:00
wg . Wait ( )
2024-04-02 13:42:40 -04:00
}
2023-11-24 14:46:26 -05:00
2024-04-02 13:42:40 -04:00
// Must be called with sp.mtx held.
func ( sp * scrapePool ) checkSymbolTable ( ) {
2023-11-24 14:46:26 -05:00
// Here we take steps to clear out the symbol table if it has grown a lot.
// After waiting some time for things to settle, we take the size of the symbol-table.
// If, after some more time, the table has grown to twice that size, we start a new one.
const minTimeToCleanSymbolTable = 5 * time . Minute
if time . Since ( sp . lastSymbolTableCheck ) > minTimeToCleanSymbolTable {
if sp . initialSymbolTableLen == 0 {
sp . initialSymbolTableLen = sp . symbolTable . Len ( )
} else if sp . symbolTable . Len ( ) > 2 * sp . initialSymbolTableLen {
sp . symbolTable = labels . NewSymbolTable ( )
sp . initialSymbolTableLen = 0
2024-04-02 12:07:00 -04:00
sp . restartLoops ( false ) // To drop all caches.
2023-11-24 14:46:26 -05:00
}
sp . lastSymbolTableCheck = time . Now ( )
}
2016-02-23 07:34:24 -05:00
}
2016-11-22 06:48:30 -05:00
// Sync converts target groups into actual scrape targets and synchronizes
2018-04-09 10:18:25 -04:00
// the currently running scraper with the resulting set and returns all scraped and dropped targets.
2018-09-26 05:20:56 -04:00
func ( sp * scrapePool ) Sync ( tgs [ ] * targetgroup . Group ) {
2020-11-12 11:06:25 -05:00
sp . mtx . Lock ( )
defer sp . mtx . Unlock ( )
2016-11-22 06:48:30 -05:00
start := time . Now ( )
2020-10-26 10:46:20 -04:00
sp . targetMtx . Lock ( )
2016-11-22 06:48:30 -05:00
var all [ ] * Target
2023-03-07 04:23:34 -05:00
var targets [ ] * Target
2023-11-23 14:02:37 -05:00
lb := labels . NewBuilderWithSymbolTable ( sp . symbolTable )
2018-01-04 09:13:31 -05:00
sp . droppedTargets = [ ] * Target { }
2023-08-14 10:39:25 -04:00
sp . droppedTargetsCount = 0
2016-11-22 06:48:30 -05:00
for _ , tg := range tgs {
2024-09-14 14:04:33 -04:00
targets , failures := TargetsFromGroup ( tg , sp . config , targets , lb )
2021-05-28 17:50:59 -04:00
for _ , err := range failures {
2024-09-09 21:41:53 -04:00
sp . logger . Error ( "Creating target failed" , "err" , err )
2016-11-22 06:48:30 -05:00
}
2023-09-22 12:47:44 -04:00
sp . metrics . targetSyncFailed . WithLabelValues ( sp . config . JobName ) . Add ( float64 ( len ( failures ) ) )
2017-12-04 10:12:28 -05:00
for _ , t := range targets {
2023-03-07 12:11:24 -05:00
// Replicate .Labels().IsEmpty() with a loop here to avoid generating garbage.
nonEmpty := false
2025-08-04 02:20:57 -04:00
t . LabelsRange ( func ( labels . Label ) { nonEmpty = true } )
style: Replace `else if` cascades with `switch`
Wiser coders than myself have come to the conclusion that a `switch`
statement is almost always superior to a statement that includes any
`else if`.
The exceptions that I have found in our codebase are just these two:
* The `if else` is followed by an additional statement before the next
condition (separated by a `;`).
* The whole thing is within a `for` loop and `break` statements are
used. In this case, using `switch` would require tagging the `for`
loop, which probably tips the balance.
Why are `switch` statements more readable?
For one, fewer curly braces. But more importantly, the conditions all
have the same alignment, so the whole thing follows the natural flow
of going down a list of conditions. With `else if`, in contrast, all
conditions but the first are "hidden" behind `} else if `, harder to
spot and (for no good reason) presented differently from the first
condition.
I'm sure the aforemention wise coders can list even more reasons.
In any case, I like it so much that I have found myself recommending
it in code reviews. I would like to make it a habit in our code base,
without making it a hard requirement that we would test on the CI. But
for that, there has to be a role model, so this commit eliminates all
`if else` occurrences, unless it is autogenerated code or fits one of
the exceptions above.
Signed-off-by: beorn7 <beorn@grafana.com>
2023-04-12 10:14:31 -04:00
switch {
case nonEmpty :
2017-12-04 10:12:28 -05:00
all = append ( all , t )
2024-12-21 08:33:08 -05:00
default :
2023-08-20 09:30:36 -04:00
if sp . config . KeepDroppedTargets == 0 || uint ( len ( sp . droppedTargets ) ) < sp . config . KeepDroppedTargets {
2023-08-14 10:39:25 -04:00
sp . droppedTargets = append ( sp . droppedTargets , t )
}
sp . droppedTargetsCount ++
2017-12-04 10:12:28 -05:00
}
}
2016-11-22 06:48:30 -05:00
}
2024-04-02 09:56:19 -04:00
sp . metrics . targetScrapePoolSymbolTableItems . WithLabelValues ( sp . config . JobName ) . Set ( float64 ( sp . symbolTable . Len ( ) ) )
2020-10-26 10:46:20 -04:00
sp . targetMtx . Unlock ( )
2016-11-22 06:48:30 -05:00
sp . sync ( all )
2024-04-02 13:42:40 -04:00
sp . checkSymbolTable ( )
2016-11-22 06:48:30 -05:00
2023-09-22 12:47:44 -04:00
sp . metrics . targetSyncIntervalLength . WithLabelValues ( sp . config . JobName ) . Observe (
2016-11-22 06:48:30 -05:00
time . Since ( start ) . Seconds ( ) ,
)
2025-11-27 12:45:35 -05:00
sp . metrics . targetSyncIntervalLengthHistogram . WithLabelValues ( sp . config . JobName ) . Observe (
time . Since ( start ) . Seconds ( ) ,
)
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolSyncsCounter . WithLabelValues ( sp . config . JobName ) . Inc ( )
2016-11-22 06:48:30 -05:00
}
2016-02-23 08:37:25 -05:00
// sync takes a list of potentially duplicated targets, deduplicates them, starts
// scrape loops for new targets, and stops scrape loops for disappeared targets.
// It returns after all stopped scrape loops terminated.
func ( sp * scrapePool ) sync ( targets [ ] * Target ) {
2025-12-22 04:38:48 -05:00
uniqueLoops := make ( map [ uint64 ] loop )
2016-02-22 10:46:55 -05:00
2020-10-26 10:46:20 -04:00
sp . targetMtx . Lock ( )
2025-12-22 04:38:48 -05:00
escapingScheme , _ := config . ToEscapingScheme ( sp . config . MetricNameEscapingScheme , sp . config . MetricNameValidationScheme )
2016-02-23 08:37:25 -05:00
for _ , t := range targets {
2016-02-28 13:56:18 -05:00
hash := t . hash ( )
2016-02-23 08:37:25 -05:00
2018-09-26 05:20:56 -04:00
if _ , ok := sp . activeTargets [ hash ] ; ! ok {
2021-08-31 11:37:32 -04:00
// The scrape interval and timeout labels are set to the config's values initially,
// so whether changed via relabeling or not, they'll exist and hold the correct values
// for every target.
var err error
2025-12-22 04:38:48 -05:00
targetInterval , targetTimeout , err := t . intervalAndTimeout (
time . Duration ( sp . config . ScrapeInterval ) ,
time . Duration ( sp . config . ScrapeTimeout ) ,
)
2019-03-12 06:26:18 -04:00
l := sp . newLoop ( scrapeLoopOptions {
2025-12-22 04:38:48 -05:00
target : t ,
scraper : & targetScraper {
Target : t ,
client : sp . client ,
timeout : targetTimeout ,
bodySizeLimit : int64 ( sp . config . BodySizeLimit ) ,
acceptHeader : acceptHeader ( sp . config . ScrapeProtocols , escapingScheme ) ,
acceptEncodingHeader : acceptEncodingHeader ( sp . config . EnableCompression ) ,
metrics : sp . metrics ,
} ,
cache : newScrapeCache ( sp . metrics ) ,
interval : targetInterval ,
timeout : targetTimeout ,
sp : sp ,
2019-03-12 06:26:18 -04:00
} )
2021-08-31 11:37:32 -04:00
if err != nil {
l . setForcedError ( err )
}
2024-08-26 05:41:56 -04:00
l . setScrapeFailureLogger ( sp . scrapeFailureLogger )
2016-02-23 08:37:25 -05:00
2018-09-26 05:20:56 -04:00
sp . activeTargets [ hash ] = t
2016-02-28 13:56:18 -05:00
sp . loops [ hash ] = l
2016-02-23 08:37:25 -05:00
2020-07-30 08:20:24 -04:00
uniqueLoops [ hash ] = l
2018-02-07 05:29:27 -05:00
} else {
2020-07-30 08:20:24 -04:00
// This might be a duplicated target.
if _ , ok := uniqueLoops [ hash ] ; ! ok {
uniqueLoops [ hash ] = nil
}
2024-12-21 08:33:08 -05:00
// Need to keep the most updated ScrapeConfig for
// displaying labels in the Service Discovery web page.
sp . activeTargets [ hash ] . SetScrapeConfig ( sp . config , t . tLabels , t . tgLabels )
2016-02-22 10:46:55 -05:00
}
}
2016-02-23 08:37:25 -05:00
var wg sync . WaitGroup
2016-02-22 10:46:55 -05:00
2016-02-23 08:37:25 -05:00
// Stop and remove old targets and scraper loops.
2018-09-26 05:20:56 -04:00
for hash := range sp . activeTargets {
2020-07-30 08:20:24 -04:00
if _ , ok := uniqueLoops [ hash ] ; ! ok {
2016-02-23 08:37:25 -05:00
wg . Add ( 1 )
go func ( l loop ) {
l . stop ( )
2016-02-22 10:46:55 -05:00
wg . Done ( )
2016-02-28 13:56:18 -05:00
} ( sp . loops [ hash ] )
2016-02-23 08:37:25 -05:00
2016-02-28 13:56:18 -05:00
delete ( sp . loops , hash )
2018-09-26 05:20:56 -04:00
delete ( sp . activeTargets , hash )
2016-02-22 10:46:55 -05:00
}
}
2020-10-26 10:46:20 -04:00
sp . targetMtx . Unlock ( )
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolTargetsAdded . WithLabelValues ( sp . config . JobName ) . Set ( float64 ( len ( uniqueLoops ) ) )
2020-07-30 08:20:24 -04:00
forcedErr := sp . refreshTargetLimitErr ( )
for _ , l := range sp . loops {
l . setForcedError ( forcedErr )
}
for _ , l := range uniqueLoops {
if l != nil {
2021-08-31 11:37:32 -04:00
go l . run ( nil )
2020-07-30 08:20:24 -04:00
}
}
2016-02-22 10:46:55 -05:00
// Wait for all potentially stopped scrapers to terminate.
// This covers the case of flapping targets. If the server is under high load, a new scraper
// may be active and tries to insert. The old scraper that didn't terminate yet could still
// be inserting a previous sample set.
wg . Wait ( )
}
2020-07-30 08:20:24 -04:00
// refreshTargetLimitErr returns an error that can be passed to the scrape loops
// if the number of targets exceeds the configured limit.
func ( sp * scrapePool ) refreshTargetLimitErr ( ) error {
2021-07-27 06:48:55 -04:00
if sp . config == nil || sp . config . TargetLimit == 0 {
2020-07-30 08:20:24 -04:00
return nil
}
2021-07-27 06:48:55 -04:00
if l := len ( sp . activeTargets ) ; l > int ( sp . config . TargetLimit ) {
2023-09-22 12:47:44 -04:00
sp . metrics . targetScrapePoolExceededTargetLimit . Inc ( )
2021-07-27 06:48:55 -04:00
return fmt . Errorf ( "target_limit exceeded (number of targets: %d, limit: %d)" , l , sp . config . TargetLimit )
2020-07-30 08:20:24 -04:00
}
2021-07-27 06:48:55 -04:00
return nil
2020-07-30 08:20:24 -04:00
}
2025-10-30 06:58:31 -04:00
func ( sp * scrapePool ) disableEndOfRunStalenessMarkers ( targets [ ] * Target ) {
sp . mtx . Lock ( )
defer sp . mtx . Unlock ( )
for i := range targets {
if l , ok := sp . loops [ targets [ i ] . hash ( ) ] ; ok {
l . disableEndOfRunStalenessMarkers ( )
}
}
}
2021-05-06 04:56:21 -04:00
func verifyLabelLimits ( lset labels . Labels , limits * labelLimits ) error {
if limits == nil {
return nil
}
2025-12-22 04:38:48 -05:00
met := lset . Get ( model . MetricNameLabel )
2021-05-06 04:56:21 -04:00
if limits . labelLimit > 0 {
2022-03-09 17:26:24 -05:00
nbLabels := lset . Len ( )
2023-04-09 03:08:40 -04:00
if nbLabels > limits . labelLimit {
2022-03-09 08:27:50 -05:00
return fmt . Errorf ( "label_limit exceeded (metric: %.50s, number of labels: %d, limit: %d)" , met , nbLabels , limits . labelLimit )
2021-05-06 04:56:21 -04:00
}
}
if limits . labelNameLengthLimit == 0 && limits . labelValueLengthLimit == 0 {
return nil
}
2022-03-09 17:26:24 -05:00
return lset . Validate ( func ( l labels . Label ) error {
2021-05-06 04:56:21 -04:00
if limits . labelNameLengthLimit > 0 {
nameLength := len ( l . Name )
2023-04-09 03:08:40 -04:00
if nameLength > limits . labelNameLengthLimit {
2022-03-09 08:27:50 -05:00
return fmt . Errorf ( "label_name_length_limit exceeded (metric: %.50s, label name: %.50s, length: %d, limit: %d)" , met , l . Name , nameLength , limits . labelNameLengthLimit )
2021-05-06 04:56:21 -04:00
}
}
if limits . labelValueLengthLimit > 0 {
valueLength := len ( l . Value )
2023-04-09 03:08:40 -04:00
if valueLength > limits . labelValueLengthLimit {
2022-03-09 08:27:50 -05:00
return fmt . Errorf ( "label_value_length_limit exceeded (metric: %.50s, label name: %.50s, value: %.50q, length: %d, limit: %d)" , met , l . Name , l . Value , valueLength , limits . labelValueLengthLimit )
2021-05-06 04:56:21 -04:00
}
}
2022-03-09 17:26:24 -05:00
return nil
} )
2021-05-06 04:56:21 -04:00
}
2018-12-18 06:26:36 -05:00
func mutateSampleLabels ( lset labels . Labels , target * Target , honor bool , rc [ ] * relabel . Config ) labels . Labels {
2017-09-08 08:34:45 -04:00
lb := labels . NewBuilder ( lset )
2017-01-30 11:30:28 -05:00
2018-04-12 10:54:53 -04:00
if honor {
2023-03-07 12:11:24 -05:00
target . LabelsRange ( func ( l labels . Label ) {
2018-02-14 12:03:58 -05:00
if ! lset . Has ( l . Name ) {
2017-09-08 08:34:45 -04:00
lb . Set ( l . Name , l . Value )
}
2022-03-09 17:26:24 -05:00
} )
2017-09-08 08:34:45 -04:00
} else {
2022-03-09 17:26:24 -05:00
var conflictingExposedLabels [ ] labels . Label
2023-03-07 12:11:24 -05:00
target . LabelsRange ( func ( l labels . Label ) {
2019-08-13 06:19:17 -04:00
existingValue := lset . Get ( l . Name )
2019-11-20 10:50:05 -05:00
if existingValue != "" {
2021-10-15 14:31:03 -04:00
conflictingExposedLabels = append ( conflictingExposedLabels , labels . Label { Name : l . Name , Value : existingValue } )
2019-11-20 10:50:05 -05:00
}
2019-08-13 06:19:17 -04:00
// It is now safe to set the target label.
2017-09-08 08:34:45 -04:00
lb . Set ( l . Name , l . Value )
2022-03-09 17:26:24 -05:00
} )
2021-10-15 14:31:03 -04:00
if len ( conflictingExposedLabels ) > 0 {
2023-03-07 12:11:24 -05:00
resolveConflictingExposedLabels ( lb , conflictingExposedLabels )
2021-10-15 14:31:03 -04:00
}
2017-01-30 11:30:28 -05:00
}
2026-01-07 09:27:01 -05:00
if keep := relabel . ProcessBuilder ( lb , rc ... ) ; ! keep {
return labels . EmptyLabels ( )
}
2017-09-08 08:34:45 -04:00
2025-11-13 13:16:29 -05:00
return lb . Labels ( )
2017-09-08 08:34:45 -04:00
}
2023-03-07 12:11:24 -05:00
func resolveConflictingExposedLabels ( lb * labels . Builder , conflictingExposedLabels [ ] labels . Label ) {
2023-09-21 16:53:51 -04:00
slices . SortStableFunc ( conflictingExposedLabels , func ( a , b labels . Label ) int {
return len ( a . Name ) - len ( b . Name )
2021-10-15 14:31:03 -04:00
} )
2023-03-07 12:11:24 -05:00
for _ , l := range conflictingExposedLabels {
2021-10-15 15:56:48 -04:00
newName := l . Name
for {
newName = model . ExportedLabelPrefix + newName
2023-03-07 12:11:24 -05:00
if lb . Get ( newName ) == "" {
lb . Set ( newName , l . Value )
2021-10-15 15:56:48 -04:00
break
}
}
2021-10-15 14:31:03 -04:00
}
2022-03-09 17:26:24 -05:00
}
2018-04-12 10:54:53 -04:00
func mutateReportSampleLabels ( lset labels . Labels , target * Target ) labels . Labels {
2017-09-08 08:34:45 -04:00
lb := labels . NewBuilder ( lset )
2023-03-07 12:11:24 -05:00
target . LabelsRange ( func ( l labels . Label ) {
2019-08-13 06:19:17 -04:00
lb . Set ( model . ExportedLabelPrefix + l . Name , lset . Get ( l . Name ) )
2017-09-08 08:34:45 -04:00
lb . Set ( l . Name , l . Value )
2022-03-09 17:26:24 -05:00
} )
2017-09-08 08:34:45 -04:00
2023-03-22 11:46:02 -04:00
return lb . Labels ( )
2016-02-28 03:51:02 -05:00
}
2025-12-22 04:38:48 -05:00
// appenderWithLimits returns an appender with additional validation.
func appenderWithLimits ( app storage . Appender , sampleLimit , bucketLimit int , maxSchema int32 ) storage . Appender {
2017-09-08 08:34:45 -04:00
app = & timeLimitAppender {
2016-12-30 15:35:35 -05:00
Appender : app ,
2017-09-08 08:34:45 -04:00
maxTime : timestamp . FromTime ( time . Now ( ) . Add ( maxAheadTime ) ) ,
}
2023-05-04 14:29:50 -04:00
// The sampleLimit is applied after metrics are potentially dropped via relabeling.
if sampleLimit > 0 {
2017-09-08 08:34:45 -04:00
app = & limitAppender {
Appender : app ,
2023-05-04 14:29:50 -04:00
limit : sampleLimit ,
2017-09-08 08:34:45 -04:00
}
2016-02-28 03:51:02 -05:00
}
2023-04-21 15:14:19 -04:00
if bucketLimit > 0 {
app = & bucketLimitAppender {
Appender : app ,
limit : bucketLimit ,
}
}
2024-01-17 10:58:54 -05:00
2024-02-28 08:06:43 -05:00
if maxSchema < histogram . ExponentialSchemaMax {
2024-01-17 10:58:54 -05:00
app = & maxSchemaAppender {
Appender : app ,
maxSchema : maxSchema ,
}
}
2017-09-08 08:34:45 -04:00
return app
2016-02-28 03:51:02 -05:00
}
2016-02-25 07:58:46 -05:00
// A scraper retrieves samples and accepts a status report at the end.
type scraper interface {
2023-10-09 12:23:53 -04:00
scrape ( ctx context . Context ) ( * http . Response , error )
readResponse ( ctx context . Context , resp * http . Response , w io . Writer ) ( string , error )
2019-11-11 16:42:24 -05:00
Report ( start time . Time , dur time . Duration , err error )
2023-05-25 05:49:43 -04:00
offset ( interval time . Duration , offsetSeed uint64 ) time . Duration
2016-02-25 07:58:46 -05:00
}
2016-02-28 13:21:50 -05:00
// targetScraper implements the scraper interface for a target.
type targetScraper struct {
* Target
2017-04-04 13:26:28 -04:00
client * http . Client
2017-04-27 04:19:55 -04:00
req * http . Request
2017-04-04 13:26:28 -04:00
timeout time . Duration
2017-01-15 11:33:07 -05:00
2017-02-22 07:00:51 -05:00
gzipr * gzip . Reader
buf * bufio . Reader
2021-05-15 22:19:22 -04:00
2023-11-20 07:02:53 -05:00
bodySizeLimit int64
acceptHeader string
acceptEncodingHeader string
2023-09-22 12:47:44 -04:00
metrics * scrapeMetrics
2017-01-15 11:33:07 -05:00
}
2021-05-15 22:19:22 -04:00
var errBodySizeLimit = errors . New ( "body size limit exceeded" )
2023-10-10 06:16:55 -04:00
// acceptHeader transforms preference from the options into specific header values as
// https://www.rfc-editor.org/rfc/rfc9110.html#name-accept defines.
// No validation is here, we expect scrape protocols to be validated already.
2025-03-26 18:27:28 -04:00
func acceptHeader ( sps [ ] config . ScrapeProtocol , scheme model . EscapingScheme ) string {
2023-10-10 06:16:55 -04:00
var vals [ ] string
weight := len ( config . ScrapeProtocolsHeaders ) + 1
for _ , sp := range sps {
2024-07-18 14:08:21 -04:00
val := config . ScrapeProtocolsHeaders [ sp ]
2025-03-26 18:27:28 -04:00
// Escaping header is only valid for newer versions of the text formats.
if sp == config . PrometheusText1_0_0 || sp == config . OpenMetricsText1_0_0 {
val += ";" + model . EscapingKey + "=" + scheme . String ( )
2024-07-18 14:08:21 -04:00
}
val += fmt . Sprintf ( ";q=0.%d" , weight )
vals = append ( vals , val )
2023-10-10 06:16:55 -04:00
weight --
}
// Default match anything.
2023-12-19 13:58:59 -05:00
vals = append ( vals , fmt . Sprintf ( "*/*;q=0.%d" , weight ) )
2023-10-10 06:16:55 -04:00
return strings . Join ( vals , "," )
}
2017-01-15 11:33:07 -05:00
2023-11-20 07:02:53 -05:00
func acceptEncodingHeader ( enableCompression bool ) string {
if enableCompression {
return "gzip"
}
return "identity"
}
2024-12-05 00:47:15 -05:00
var UserAgent = version . PrometheusUserAgent ( )
2017-02-28 08:59:33 -05:00
2023-10-09 12:23:53 -04:00
func ( s * targetScraper ) scrape ( ctx context . Context ) ( * http . Response , error ) {
2017-02-22 07:00:51 -05:00
if s . req == nil {
2024-04-08 15:26:23 -04:00
req , err := http . NewRequest ( http . MethodGet , s . URL ( ) . String ( ) , nil )
2017-02-22 07:00:51 -05:00
if err != nil {
2023-10-09 12:23:53 -04:00
return nil , err
2017-02-22 07:00:51 -05:00
}
2022-10-12 03:48:25 -04:00
req . Header . Add ( "Accept" , s . acceptHeader )
2023-11-20 07:02:53 -05:00
req . Header . Add ( "Accept-Encoding" , s . acceptEncodingHeader )
2021-09-13 14:10:14 -04:00
req . Header . Set ( "User-Agent" , UserAgent )
2021-06-18 03:38:12 -04:00
req . Header . Set ( "X-Prometheus-Scrape-Timeout-Seconds" , strconv . FormatFloat ( s . timeout . Seconds ( ) , 'f' , - 1 , 64 ) )
2017-02-22 07:00:51 -05:00
s . req = req
2016-02-28 13:21:50 -05:00
}
2025-07-15 03:37:24 -04:00
ctx , span := otel . Tracer ( "" ) . Start ( ctx , "Scrape" , trace . WithSpanKind ( trace . SpanKindClient ) )
defer span . End ( )
2017-08-09 10:30:49 -04:00
2023-10-09 12:23:53 -04:00
return s . client . Do ( s . req . WithContext ( ctx ) )
}
2025-02-10 02:06:58 -05:00
func ( s * targetScraper ) readResponse ( _ context . Context , resp * http . Response , w io . Writer ) ( string , error ) {
2019-04-18 04:50:37 -04:00
defer func ( ) {
2022-04-27 05:24:36 -04:00
io . Copy ( io . Discard , resp . Body )
2019-04-18 04:50:37 -04:00
resp . Body . Close ( )
} ( )
2016-02-28 13:21:50 -05:00
if resp . StatusCode != http . StatusOK {
2023-11-01 15:06:46 -04:00
return "" , fmt . Errorf ( "server returned HTTP status %s" , resp . Status )
2016-02-28 13:21:50 -05:00
}
2021-05-15 22:19:22 -04:00
if s . bodySizeLimit <= 0 {
s . bodySizeLimit = math . MaxInt64
}
2017-02-22 07:00:51 -05:00
if resp . Header . Get ( "Content-Encoding" ) != "gzip" {
2021-05-15 22:19:22 -04:00
n , err := io . Copy ( w , io . LimitReader ( resp . Body , s . bodySizeLimit ) )
2018-11-26 08:05:07 -05:00
if err != nil {
return "" , err
}
2021-05-15 22:19:22 -04:00
if n >= s . bodySizeLimit {
2023-09-22 12:47:44 -04:00
s . metrics . targetScrapeExceededBodySizeLimit . Inc ( )
2021-05-15 22:19:22 -04:00
return "" , errBodySizeLimit
}
2018-11-26 08:05:07 -05:00
return resp . Header . Get ( "Content-Type" ) , nil
2017-02-22 07:00:51 -05:00
}
if s . gzipr == nil {
s . buf = bufio . NewReader ( resp . Body )
2023-10-09 12:23:53 -04:00
var err error
2017-02-22 07:00:51 -05:00
s . gzipr , err = gzip . NewReader ( s . buf )
if err != nil {
2018-10-04 09:52:03 -04:00
return "" , err
2017-02-22 07:00:51 -05:00
}
} else {
s . buf . Reset ( resp . Body )
2023-10-09 12:23:53 -04:00
if err := s . gzipr . Reset ( s . buf ) ; err != nil {
2018-10-04 09:52:03 -04:00
return "" , err
2018-08-17 11:24:35 -04:00
}
2017-02-22 07:00:51 -05:00
}
2021-05-15 22:19:22 -04:00
n , err := io . Copy ( w , io . LimitReader ( s . gzipr , s . bodySizeLimit ) )
2017-02-22 07:00:51 -05:00
s . gzipr . Close ( )
2018-10-04 09:52:03 -04:00
if err != nil {
return "" , err
}
2021-05-15 22:19:22 -04:00
if n >= s . bodySizeLimit {
2023-09-22 12:47:44 -04:00
s . metrics . targetScrapeExceededBodySizeLimit . Inc ( )
2021-05-15 22:19:22 -04:00
return "" , errBodySizeLimit
}
2018-10-04 09:52:03 -04:00
return resp . Header . Get ( "Content-Type" ) , nil
2016-02-28 13:21:50 -05:00
}
2016-02-28 03:51:02 -05:00
// A loop can run and be stopped again. It must not be reused after it was stopped.
2016-02-22 10:46:55 -05:00
type loop interface {
2021-08-31 11:37:32 -04:00
run ( errc chan <- error )
2020-07-30 08:20:24 -04:00
setForcedError ( err error )
2024-11-23 23:30:23 -05:00
setScrapeFailureLogger ( FailureLogger )
2016-02-22 10:46:55 -05:00
stop ( )
2020-01-22 07:13:47 -05:00
getCache ( ) * scrapeCache
2020-03-20 12:43:26 -04:00
disableEndOfRunStalenessMarkers ( )
2016-02-22 10:46:55 -05:00
}
2017-09-15 05:08:51 -04:00
type cacheEntry struct {
2021-11-06 06:10:04 -04:00
ref storage . SeriesRef
2017-05-26 02:44:24 -04:00
lastIter uint64
2017-09-15 05:08:51 -04:00
hash uint64
lset labels . Labels
2017-04-13 13:07:23 -04:00
}
2016-02-22 10:46:55 -05:00
type scrapeLoop struct {
2025-12-22 04:38:48 -05:00
// Parameters.
2022-05-03 14:45:52 -04:00
ctx context . Context
cancel func ( )
stopped chan struct { }
2025-12-22 04:38:48 -05:00
parentCtx context . Context
appenderCtx context . Context
l * slog . Logger
cache * scrapeCache
2020-03-20 12:43:26 -04:00
2025-12-22 04:38:48 -05:00
interval time . Duration
timeout time . Duration
sampleMutator labelsMutator
reportSampleMutator labelsMutator
scraper scraper
// Static params per scrapePool.
2026-01-21 03:21:56 -05:00
appendable storage . Appendable
appendableV2 storage . AppendableV2
buffers * pool . Pool
offsetSeed uint64
symbolTable * labels . SymbolTable
metrics * scrapeMetrics
2025-12-22 04:38:48 -05:00
// Options from config.ScrapeConfig.
sampleLimit int
bucketLimit int
maxSchema int32
labelLimits * labelLimits
honorLabels bool
honorTimestamps bool
trackTimestampsStaleness bool
enableNativeHistogramScraping bool
alwaysScrapeClassicHist bool
convertClassicHistToNHCB bool
fallbackScrapeProtocol string
enableCompression bool
mrc [ ] * relabel . Config
validationScheme model . ValidationScheme
// Options from scrape.Options.
enableSTZeroIngestion bool
2026-02-18 04:15:14 -05:00
parseST bool // Used by AppenderV2 only.
2025-12-22 04:38:48 -05:00
enableTypeAndUnitLabels bool
reportExtraMetrics bool
appendMetadataToWAL bool
passMetadataInContext bool
skipOffsetting bool // For testability.
// error injection through setForcedError.
forcedErr error
forcedErrMtx sync . Mutex
// Special logger set on setScrapeFailureLogger
scrapeFailureLoggerMtx sync . RWMutex
scrapeFailureLogger FailureLogger
2023-12-11 03:43:42 -05:00
2025-12-22 04:38:48 -05:00
// Locally cached data.
lastScrapeSize int
disabledEndOfRunStalenessMarkers atomic . Bool
2017-05-26 04:44:48 -04:00
}
// scrapeCache tracks mappings of exposed metric strings to label sets and
// storage references. Additionally, it tracks staleness of series between
// scrapes.
2025-01-15 06:33:42 -05:00
// Cache is meant to be used per a single target.
2017-05-26 04:44:48 -04:00
type scrapeCache struct {
iter uint64 // Current scrape iteration.
2019-03-28 13:52:46 -04:00
// How many series and metadata entries there were at the last success.
successfulCount int
2017-09-15 05:08:51 -04:00
// Parsed string to an entry with information about the actual label set
// and its storage reference.
2018-05-18 03:32:11 -04:00
series map [ string ] * cacheEntry
2017-05-24 10:23:48 -04:00
2017-09-08 08:34:45 -04:00
// Cache of dropped metric strings and their iteration. The iteration must
2023-01-04 07:05:42 -05:00
// be a pointer so we can update it.
2018-05-18 03:32:11 -04:00
droppedSeries map [ string ] * uint64
2017-09-08 08:34:45 -04:00
2025-09-02 10:17:24 -04:00
// Series that were seen in the current and previous scrape, for staleness detection.
seriesCur map [ storage . SeriesRef ] * cacheEntry
seriesPrev map [ storage . SeriesRef ] * cacheEntry
2018-05-18 03:32:11 -04:00
2025-12-22 04:38:48 -05:00
// TODO(bwplotka): Consider moving metadata caching to head. See
// https://github.com/prometheus/prometheus/issues/17619.
2025-01-15 06:33:42 -05:00
metaMtx sync . Mutex // Mutex is needed due to api touching it when metadata is queried.
metadata map [ string ] * metaEntry // metadata by metric family name.
2023-09-22 12:47:44 -04:00
metrics * scrapeMetrics
2018-05-18 03:32:11 -04:00
}
// metaEntry holds meta information about a metric.
type metaEntry struct {
2022-08-31 09:50:05 -04:00
metadata . Metadata
lastIter uint64 // Last scrape iteration the entry was observed at.
lastIterChange uint64 // Last scrape iteration the entry was changed at.
2017-05-26 04:44:48 -04:00
}
2017-01-15 11:33:07 -05:00
2020-01-29 06:13:18 -05:00
func ( m * metaEntry ) size ( ) int {
// The attribute lastIter although part of the struct it is not metadata.
2022-08-31 09:50:05 -04:00
return len ( m . Help ) + len ( m . Unit ) + len ( m . Type )
2020-01-29 06:13:18 -05:00
}
2023-09-22 12:47:44 -04:00
func newScrapeCache ( metrics * scrapeMetrics ) * scrapeCache {
2017-05-26 04:44:48 -04:00
return & scrapeCache {
2018-05-18 03:32:11 -04:00
series : map [ string ] * cacheEntry { } ,
droppedSeries : map [ string ] * uint64 { } ,
2025-09-02 10:17:24 -04:00
seriesCur : map [ storage . SeriesRef ] * cacheEntry { } ,
seriesPrev : map [ storage . SeriesRef ] * cacheEntry { } ,
2018-05-18 03:32:11 -04:00
metadata : map [ string ] * metaEntry { } ,
2023-09-22 12:47:44 -04:00
metrics : metrics ,
2017-05-26 04:44:48 -04:00
}
}
2019-03-28 13:52:46 -04:00
func ( c * scrapeCache ) iterDone ( flushCache bool ) {
c . metaMtx . Lock ( )
count := len ( c . series ) + len ( c . droppedSeries ) + len ( c . metadata )
c . metaMtx . Unlock ( )
style: Replace `else if` cascades with `switch`
Wiser coders than myself have come to the conclusion that a `switch`
statement is almost always superior to a statement that includes any
`else if`.
The exceptions that I have found in our codebase are just these two:
* The `if else` is followed by an additional statement before the next
condition (separated by a `;`).
* The whole thing is within a `for` loop and `break` statements are
used. In this case, using `switch` would require tagging the `for`
loop, which probably tips the balance.
Why are `switch` statements more readable?
For one, fewer curly braces. But more importantly, the conditions all
have the same alignment, so the whole thing follows the natural flow
of going down a list of conditions. With `else if`, in contrast, all
conditions but the first are "hidden" behind `} else if `, harder to
spot and (for no good reason) presented differently from the first
condition.
I'm sure the aforemention wise coders can list even more reasons.
In any case, I like it so much that I have found myself recommending
it in code reviews. I would like to make it a habit in our code base,
without making it a hard requirement that we would test on the CI. But
for that, there has to be a role model, so this commit eliminates all
`if else` occurrences, unless it is autogenerated code or fits one of
the exceptions above.
Signed-off-by: beorn7 <beorn@grafana.com>
2023-04-12 10:14:31 -04:00
switch {
case flushCache :
2019-03-28 13:52:46 -04:00
c . successfulCount = count
style: Replace `else if` cascades with `switch`
Wiser coders than myself have come to the conclusion that a `switch`
statement is almost always superior to a statement that includes any
`else if`.
The exceptions that I have found in our codebase are just these two:
* The `if else` is followed by an additional statement before the next
condition (separated by a `;`).
* The whole thing is within a `for` loop and `break` statements are
used. In this case, using `switch` would require tagging the `for`
loop, which probably tips the balance.
Why are `switch` statements more readable?
For one, fewer curly braces. But more importantly, the conditions all
have the same alignment, so the whole thing follows the natural flow
of going down a list of conditions. With `else if`, in contrast, all
conditions but the first are "hidden" behind `} else if `, harder to
spot and (for no good reason) presented differently from the first
condition.
I'm sure the aforemention wise coders can list even more reasons.
In any case, I like it so much that I have found myself recommending
it in code reviews. I would like to make it a habit in our code base,
without making it a hard requirement that we would test on the CI. But
for that, there has to be a role model, so this commit eliminates all
`if else` occurrences, unless it is autogenerated code or fits one of
the exceptions above.
Signed-off-by: beorn7 <beorn@grafana.com>
2023-04-12 10:14:31 -04:00
case count > c . successfulCount * 2 + 1000 :
2019-03-28 13:52:46 -04:00
// If a target had varying labels in scrapes that ultimately failed,
// the caches would grow indefinitely. Force a flush when this happens.
// We use the heuristic that this is a doubling of the cache size
// since the last scrape, and allow an additional 1000 in case
// initial scrapes all fail.
flushCache = true
2023-09-22 12:47:44 -04:00
c . metrics . targetScrapeCacheFlushForced . Inc ( )
2019-03-28 13:52:46 -04:00
}
if flushCache {
2019-03-28 13:07:14 -04:00
// All caches may grow over time through series churn
// or multiple string representations of the same metric. Clean up entries
// that haven't appeared in the last scrape.
for s , e := range c . series {
if c . iter != e . lastIter {
delete ( c . series , s )
}
2017-05-26 04:44:48 -04:00
}
2019-03-28 13:07:14 -04:00
for s , iter := range c . droppedSeries {
if c . iter != * iter {
delete ( c . droppedSeries , s )
}
2017-09-08 08:34:45 -04:00
}
2019-03-28 13:07:14 -04:00
c . metaMtx . Lock ( )
for m , e := range c . metadata {
// Keep metadata around for 10 scrapes after its metric disappeared.
if c . iter - e . lastIter > 10 {
delete ( c . metadata , m )
}
2018-05-18 03:32:11 -04:00
}
2019-03-28 13:07:14 -04:00
c . metaMtx . Unlock ( )
2018-05-18 03:32:11 -04:00
}
2017-05-26 04:44:48 -04:00
2025-09-02 10:18:14 -04:00
// Swap current and previous series then clear the new current, to save allocations.
2017-05-26 04:44:48 -04:00
c . seriesPrev , c . seriesCur = c . seriesCur , c . seriesPrev
2025-09-02 10:18:14 -04:00
clear ( c . seriesCur )
2025-03-08 13:45:37 -05:00
c . iter ++
2016-02-22 10:46:55 -05:00
}
2024-02-27 07:09:32 -05:00
func ( c * scrapeCache ) get ( met [ ] byte ) ( * cacheEntry , bool , bool ) {
2022-12-20 11:54:07 -05:00
e , ok := c . series [ string ( met ) ]
2017-05-26 04:44:48 -04:00
if ! ok {
2024-02-27 07:09:32 -05:00
return nil , false , false
2017-05-26 04:44:48 -04:00
}
2024-02-27 07:09:32 -05:00
alreadyScraped := e . lastIter == c . iter
2017-05-26 04:44:48 -04:00
e . lastIter = c . iter
2024-02-27 07:09:32 -05:00
return e , true , alreadyScraped
2017-05-26 04:44:48 -04:00
}
2025-04-14 10:46:53 -04:00
func ( c * scrapeCache ) addRef ( met [ ] byte , ref storage . SeriesRef , lset labels . Labels , hash uint64 ) ( ce * cacheEntry ) {
2017-09-07 08:14:41 -04:00
if ref == 0 {
2025-04-14 10:46:53 -04:00
return nil
2017-06-26 02:56:40 -04:00
}
2025-04-14 10:46:53 -04:00
ce = & cacheEntry { ref : ref , lastIter : c . iter , lset : lset , hash : hash }
c . series [ string ( met ) ] = ce
return ce
2017-05-26 04:44:48 -04:00
}
2023-01-04 07:05:42 -05:00
func ( c * scrapeCache ) addDropped ( met [ ] byte ) {
2017-09-08 08:34:45 -04:00
iter := c . iter
2023-01-04 07:05:42 -05:00
c . droppedSeries [ string ( met ) ] = & iter
2017-09-08 08:34:45 -04:00
}
2022-12-20 11:54:07 -05:00
func ( c * scrapeCache ) getDropped ( met [ ] byte ) bool {
iterp , ok := c . droppedSeries [ string ( met ) ]
2017-09-08 08:34:45 -04:00
if ok {
* iterp = c . iter
}
return ok
}
2025-09-02 10:17:24 -04:00
func ( c * scrapeCache ) trackStaleness ( ref storage . SeriesRef , ce * cacheEntry ) {
c . seriesCur [ ref ] = ce
2017-05-26 04:44:48 -04:00
}
2025-04-14 10:46:53 -04:00
func ( c * scrapeCache ) forEachStale ( f func ( storage . SeriesRef , labels . Labels ) bool ) {
2025-09-02 10:17:24 -04:00
for ref , ce := range c . seriesPrev {
if _ , ok := c . seriesCur [ ref ] ; ! ok {
2025-04-14 10:46:53 -04:00
if ! f ( ce . ref , ce . lset ) {
2017-05-26 04:44:48 -04:00
break
}
}
}
}
2025-01-15 06:33:42 -05:00
func yoloString ( b [ ] byte ) string {
return unsafe . String ( unsafe . SliceData ( b ) , len ( b ) )
}
func ( c * scrapeCache ) setType ( mfName [ ] byte , t model . MetricType ) ( [ ] byte , * metaEntry ) {
2018-05-18 03:32:11 -04:00
c . metaMtx . Lock ( )
2025-01-15 06:33:42 -05:00
defer c . metaMtx . Unlock ( )
2018-05-18 03:32:11 -04:00
2025-07-28 09:54:32 -04:00
e , ok := c . metadata [ string ( mfName ) ]
2018-05-18 03:32:11 -04:00
if ! ok {
2023-11-22 09:39:21 -05:00
e = & metaEntry { Metadata : metadata . Metadata { Type : model . MetricTypeUnknown } }
2025-01-15 06:33:42 -05:00
c . metadata [ string ( mfName ) ] = e
2018-05-18 03:32:11 -04:00
}
2022-08-31 09:50:05 -04:00
if e . Type != t {
e . Type = t
e . lastIterChange = c . iter
}
2018-05-18 03:32:11 -04:00
e . lastIter = c . iter
2025-01-15 06:33:42 -05:00
return mfName , e
2018-05-18 03:32:11 -04:00
}
2025-01-15 06:33:42 -05:00
func ( c * scrapeCache ) setHelp ( mfName , help [ ] byte ) ( [ ] byte , * metaEntry ) {
2018-05-18 03:32:11 -04:00
c . metaMtx . Lock ( )
2025-01-15 06:33:42 -05:00
defer c . metaMtx . Unlock ( )
2018-05-18 03:32:11 -04:00
2025-07-28 09:54:32 -04:00
e , ok := c . metadata [ string ( mfName ) ]
2018-05-18 03:32:11 -04:00
if ! ok {
2023-11-22 09:39:21 -05:00
e = & metaEntry { Metadata : metadata . Metadata { Type : model . MetricTypeUnknown } }
2025-01-15 06:33:42 -05:00
c . metadata [ string ( mfName ) ] = e
2018-05-18 03:32:11 -04:00
}
2022-12-20 11:54:07 -05:00
if e . Help != string ( help ) {
2022-08-31 09:50:05 -04:00
e . Help = string ( help )
e . lastIterChange = c . iter
2018-05-18 03:32:11 -04:00
}
e . lastIter = c . iter
2025-01-15 06:33:42 -05:00
return mfName , e
2018-05-18 03:32:11 -04:00
}
2025-01-15 06:33:42 -05:00
func ( c * scrapeCache ) setUnit ( mfName , unit [ ] byte ) ( [ ] byte , * metaEntry ) {
2018-10-05 12:11:16 -04:00
c . metaMtx . Lock ( )
2025-01-15 06:33:42 -05:00
defer c . metaMtx . Unlock ( )
2018-10-05 12:11:16 -04:00
2025-07-28 09:54:32 -04:00
e , ok := c . metadata [ string ( mfName ) ]
2018-10-05 12:11:16 -04:00
if ! ok {
2023-11-22 09:39:21 -05:00
e = & metaEntry { Metadata : metadata . Metadata { Type : model . MetricTypeUnknown } }
2025-01-15 06:33:42 -05:00
c . metadata [ string ( mfName ) ] = e
2018-10-05 12:11:16 -04:00
}
2022-12-20 11:54:07 -05:00
if e . Unit != string ( unit ) {
2022-08-31 09:50:05 -04:00
e . Unit = string ( unit )
e . lastIterChange = c . iter
2018-10-05 12:11:16 -04:00
}
e . lastIter = c . iter
2025-01-15 06:33:42 -05:00
return mfName , e
2018-10-05 12:11:16 -04:00
}
2025-01-15 06:33:42 -05:00
// GetMetadata returns metadata given the metric family name.
func ( c * scrapeCache ) GetMetadata ( mfName string ) ( MetricMetadata , bool ) {
2018-05-18 03:32:11 -04:00
c . metaMtx . Lock ( )
defer c . metaMtx . Unlock ( )
2025-01-15 06:33:42 -05:00
m , ok := c . metadata [ mfName ]
2018-05-18 03:32:11 -04:00
if ! ok {
return MetricMetadata { } , false
}
return MetricMetadata {
2025-01-15 06:33:42 -05:00
MetricFamily : mfName ,
Type : m . Type ,
Help : m . Help ,
Unit : m . Unit ,
2018-05-18 03:32:11 -04:00
} , true
}
2025-01-15 06:33:42 -05:00
// ListMetadata lists metadata.
2019-12-04 10:18:27 -05:00
func ( c * scrapeCache ) ListMetadata ( ) [ ] MetricMetadata {
2018-05-18 03:32:11 -04:00
c . metaMtx . Lock ( )
defer c . metaMtx . Unlock ( )
2018-06-05 06:30:19 -04:00
res := make ( [ ] MetricMetadata , 0 , len ( c . metadata ) )
2018-05-18 03:32:11 -04:00
for m , e := range c . metadata {
res = append ( res , MetricMetadata {
2025-01-15 06:33:42 -05:00
MetricFamily : m ,
Type : e . Type ,
Help : e . Help ,
Unit : e . Unit ,
2018-05-18 03:32:11 -04:00
} )
}
return res
}
2025-01-15 06:33:42 -05:00
// SizeMetadata returns the size of the metadata cache.
2020-01-29 06:13:18 -05:00
func ( c * scrapeCache ) SizeMetadata ( ) ( s int ) {
c . metaMtx . Lock ( )
defer c . metaMtx . Unlock ( )
for _ , e := range c . metadata {
s += e . size ( )
}
return s
}
2025-01-15 06:33:42 -05:00
// LengthMetadata returns the number of metadata entries in the cache.
2020-01-29 06:13:18 -05:00
func ( c * scrapeCache ) LengthMetadata ( ) int {
c . metaMtx . Lock ( )
defer c . metaMtx . Unlock ( )
return len ( c . metadata )
}
2025-12-22 04:38:48 -05:00
// scrapeLoopOptions contains static options that do not change per scrapePool lifecycle.
type scrapeLoopOptions struct {
target * Target
scraper scraper
cache * scrapeCache
interval , timeout time . Duration
sp * scrapePool
}
2022-05-03 14:45:52 -04:00
2025-12-22 04:38:48 -05:00
// newScrapeLoop constructs new scrapeLoop.
// NOTE: Technically this could be a scrapePool method, but it's a standalone function to make it clear scrapeLoop
// can be used outside scrapePool lifecycle (e.g. in tests).
func newScrapeLoop ( opts scrapeLoopOptions ) * scrapeLoop {
// Update the targets retrieval function for metadata to a new target.
opts . target . SetMetadataStore ( opts . cache )
2022-05-03 14:45:52 -04:00
2025-12-22 04:38:48 -05:00
appenderCtx := opts . sp . ctx
if opts . sp . options . PassMetadataInContext {
2022-05-03 14:45:52 -04:00
// Store the cache and target in the context. This is then used by downstream OTel Collector
// to lookup the metadata required to process the samples. Not used by Prometheus itself.
// TODO(gouthamve) We're using a dedicated context because using the parentCtx caused a memory
// leak. We should ideally fix the main leak. See: https://github.com/prometheus/prometheus/pull/10590
2025-12-22 04:38:48 -05:00
// TODO(bwplotka): Remove once OpenTelemetry collector uses AppenderV2 (add issue)
appenderCtx = ContextWithMetricMetadataStore ( appenderCtx , opts . cache )
appenderCtx = ContextWithTarget ( appenderCtx , opts . target )
}
ctx , cancel := context . WithCancel ( opts . sp . ctx )
return & scrapeLoop {
ctx : ctx ,
cancel : cancel ,
stopped : make ( chan struct { } ) ,
parentCtx : opts . sp . ctx ,
appenderCtx : appenderCtx ,
l : opts . sp . logger . With ( "target" , opts . target ) ,
cache : opts . cache ,
interval : opts . interval ,
timeout : opts . timeout ,
sampleMutator : func ( l labels . Labels ) labels . Labels {
2025-12-22 10:28:08 -05:00
return mutateSampleLabels ( l , opts . target , opts . sp . config . HonorLabels , opts . sp . config . MetricRelabelConfigs )
2025-12-22 04:38:48 -05:00
} ,
reportSampleMutator : func ( l labels . Labels ) labels . Labels { return mutateReportSampleLabels ( l , opts . target ) } ,
scraper : opts . scraper ,
// Static params per scrapePool.
2026-01-21 03:21:56 -05:00
appendable : opts . sp . appendable ,
appendableV2 : opts . sp . appendableV2 ,
buffers : opts . sp . buffers ,
offsetSeed : opts . sp . offsetSeed ,
symbolTable : opts . sp . symbolTable ,
metrics : opts . sp . metrics ,
2025-12-22 04:38:48 -05:00
// config.ScrapeConfig.
sampleLimit : int ( opts . sp . config . SampleLimit ) ,
bucketLimit : int ( opts . sp . config . NativeHistogramBucketLimit ) ,
maxSchema : pickSchema ( opts . sp . config . NativeHistogramMinBucketFactor ) ,
labelLimits : & labelLimits {
labelLimit : int ( opts . sp . config . LabelLimit ) ,
labelNameLengthLimit : int ( opts . sp . config . LabelNameLengthLimit ) ,
labelValueLengthLimit : int ( opts . sp . config . LabelValueLengthLimit ) ,
} ,
honorLabels : opts . sp . config . HonorLabels ,
honorTimestamps : opts . sp . config . HonorTimestamps ,
trackTimestampsStaleness : opts . sp . config . TrackTimestampsStaleness ,
enableNativeHistogramScraping : opts . sp . config . ScrapeNativeHistogramsEnabled ( ) ,
alwaysScrapeClassicHist : opts . sp . config . AlwaysScrapeClassicHistogramsEnabled ( ) ,
convertClassicHistToNHCB : opts . sp . config . ConvertClassicHistogramsToNHCBEnabled ( ) ,
fallbackScrapeProtocol : opts . sp . config . ScrapeFallbackProtocol . HeaderMediaType ( ) ,
enableCompression : opts . sp . config . EnableCompression ,
mrc : opts . sp . config . MetricRelabelConfigs ,
2026-01-06 07:00:49 -05:00
reportExtraMetrics : opts . sp . config . ExtraScrapeMetricsEnabled ( ) ,
2025-12-22 04:38:48 -05:00
validationScheme : opts . sp . config . MetricNameValidationScheme ,
// scrape.Options.
2026-02-18 04:15:14 -05:00
enableSTZeroIngestion : opts . sp . options . EnableStartTimestampZeroIngestion ,
// parseST was added recently. Before EnableStartTimestampZeroIngestion
// was enabling parsing ST. For non-Prometheus users of the scrape
// manager, we ensure appenderV2 parseST is set on EnableStartTimestampZeroIngestion
// This will be removed when EnableStartTimestampZeroIngestion is removed.
parseST : opts . sp . options . ParseST || opts . sp . options . EnableStartTimestampZeroIngestion ,
2025-12-22 04:38:48 -05:00
enableTypeAndUnitLabels : opts . sp . options . EnableTypeAndUnitLabels ,
appendMetadataToWAL : opts . sp . options . AppendMetadata ,
passMetadataInContext : opts . sp . options . PassMetadataInContext ,
skipOffsetting : opts . sp . options . skipOffsetting ,
}
2016-02-22 10:46:55 -05:00
}
2024-11-23 23:30:23 -05:00
func ( sl * scrapeLoop ) setScrapeFailureLogger ( l FailureLogger ) {
2024-08-26 05:41:56 -04:00
sl . scrapeFailureLoggerMtx . Lock ( )
defer sl . scrapeFailureLoggerMtx . Unlock ( )
if ts , ok := sl . scraper . ( fmt . Stringer ) ; ok && l != nil {
2024-11-23 23:30:23 -05:00
l = slog . New ( l ) . With ( "target" , ts . String ( ) ) . Handler ( ) . ( FailureLogger )
2024-08-26 05:41:56 -04:00
}
sl . scrapeFailureLogger = l
}
2021-08-31 11:37:32 -04:00
func ( sl * scrapeLoop ) run ( errc chan <- error ) {
2023-12-11 03:43:42 -05:00
if ! sl . skipOffsetting {
select {
case <- time . After ( sl . scraper . offset ( sl . interval , sl . offsetSeed ) ) :
// Continue after a scraping offset.
case <- sl . ctx . Done ( ) :
close ( sl . stopped )
return
}
2016-02-22 10:46:55 -05:00
}
var last time . Time
2021-03-15 09:05:17 -04:00
alignedScrapeTime := time . Now ( ) . Round ( 0 )
2021-08-31 11:37:32 -04:00
ticker := time . NewTicker ( sl . interval )
2016-02-22 10:46:55 -05:00
defer ticker . Stop ( )
2017-05-10 11:59:02 -04:00
mainLoop :
2016-02-22 10:46:55 -05:00
for {
select {
2019-08-28 09:55:09 -04:00
case <- sl . parentCtx . Done ( ) :
2017-05-10 11:59:02 -04:00
close ( sl . stopped )
2016-02-22 10:46:55 -05:00
return
2019-08-28 09:55:09 -04:00
case <- sl . ctx . Done ( ) :
2017-05-10 11:59:02 -04:00
break mainLoop
2016-02-22 10:46:55 -05:00
default :
}
2020-10-05 12:17:50 -04:00
// Temporary workaround for a jitter in go timers that causes disk space
// increase in TSDB.
// See https://github.com/prometheus/prometheus/issues/7846
2021-03-15 09:05:17 -04:00
// Calling Round ensures the time used is the wall clock, as otherwise .Sub
// and .Add on time.Time behave differently (see time package docs).
scrapeTime := time . Now ( ) . Round ( 0 )
2024-02-21 09:09:21 -05:00
if AlignScrapeTimestamps {
2024-03-08 05:18:18 -05:00
// Tolerance is clamped to maximum 1% of the scrape interval.
tolerance := min ( sl . interval / 100 , ScrapeTimestampTolerance )
2020-10-06 07:48:24 -04:00
// For some reason, a tick might have been skipped, in which case we
2020-10-05 12:17:50 -04:00
// would call alignedScrapeTime.Add(interval) multiple times.
2021-08-31 11:37:32 -04:00
for scrapeTime . Sub ( alignedScrapeTime ) >= sl . interval {
alignedScrapeTime = alignedScrapeTime . Add ( sl . interval )
2020-10-05 12:17:50 -04:00
}
// Align the scrape time if we are in the tolerance boundaries.
2024-02-21 09:09:21 -05:00
if scrapeTime . Sub ( alignedScrapeTime ) <= tolerance {
2020-10-05 12:17:50 -04:00
scrapeTime = alignedScrapeTime
}
}
2021-10-24 10:38:21 -04:00
last = sl . scrapeAndReport ( last , scrapeTime , errc )
2016-02-22 12:49:26 -05:00
2020-07-16 07:53:39 -04:00
select {
case <- sl . parentCtx . Done ( ) :
close ( sl . stopped )
return
case <- sl . ctx . Done ( ) :
break mainLoop
case <- ticker . C :
2016-12-29 03:27:30 -05:00
}
2020-07-16 07:53:39 -04:00
}
2018-02-20 06:32:23 -05:00
2020-07-16 07:53:39 -04:00
close ( sl . stopped )
2016-02-22 10:46:55 -05:00
2025-10-30 06:58:31 -04:00
if ! sl . disabledEndOfRunStalenessMarkers . Load ( ) {
2021-08-31 11:37:32 -04:00
sl . endOfRunStaleness ( last , ticker , sl . interval )
2020-07-16 07:53:39 -04:00
}
}
2017-09-07 08:43:21 -04:00
2025-12-22 04:38:48 -05:00
func ( sl * scrapeLoop ) appender ( ) scrapeLoopAppendAdapter {
2026-01-21 03:21:56 -05:00
if sl . appendableV2 != nil {
return & scrapeLoopAppenderV2 { scrapeLoop : sl , AppenderV2 : sl . appendableV2 . AppenderV2 ( sl . appenderCtx ) }
}
2025-12-22 04:38:48 -05:00
return & scrapeLoopAppender { scrapeLoop : sl , Appender : sl . appendable . Appender ( sl . appenderCtx ) }
}
2020-07-16 07:53:39 -04:00
// scrapeAndReport performs a scrape and then appends the result to the storage
// together with reporting metrics, by using as few appenders as possible.
// In the happy scenario, a single appender is used.
2022-05-03 14:45:52 -04:00
// This function uses sl.appenderCtx instead of sl.ctx on purpose. A scrape should
2020-08-07 09:58:16 -04:00
// only be cancelled on shutdown, not on reloads.
2021-10-24 10:38:21 -04:00
func ( sl * scrapeLoop ) scrapeAndReport ( last , appendTime time . Time , errc chan <- error ) time . Time {
2020-07-30 08:20:24 -04:00
start := time . Now ( )
2017-06-14 22:08:03 -04:00
2020-07-16 07:53:39 -04:00
// Only record after the first scrape.
if ! last . IsZero ( ) {
2023-09-22 12:47:44 -04:00
sl . metrics . targetIntervalLength . WithLabelValues ( sl . interval . String ( ) ) . Observe (
2020-07-16 07:53:39 -04:00
time . Since ( last ) . Seconds ( ) ,
)
2025-11-27 12:45:35 -05:00
sl . metrics . targetIntervalLengthHistogram . WithLabelValues ( sl . interval . String ( ) ) . Observe (
time . Since ( last ) . Seconds ( ) ,
)
2020-07-16 07:53:39 -04:00
}
2016-02-22 10:46:55 -05:00
2023-10-09 12:23:53 -04:00
var total , added , seriesAdded , bytesRead int
2020-07-30 08:20:24 -04:00
var err , appErr , scrapeErr error
2020-07-31 13:11:08 -04:00
2025-12-22 04:38:48 -05:00
app := sl . appender ( )
2020-07-16 07:53:39 -04:00
defer func ( ) {
if err != nil {
2025-12-22 04:38:48 -05:00
_ = app . Rollback ( )
2016-02-22 10:46:55 -05:00
return
2020-07-16 07:53:39 -04:00
}
err = app . Commit ( )
2026-01-13 12:07:27 -05:00
if sl . reportExtraMetrics {
totalDuration := time . Since ( start )
// Record total scrape duration metric.
sl . metrics . targetScrapeDuration . Observe ( totalDuration . Seconds ( ) )
}
2020-07-16 07:53:39 -04:00
if err != nil {
2024-09-09 21:41:53 -04:00
sl . l . Error ( "Scrape commit failed" , "err" , err )
2020-07-16 07:53:39 -04:00
}
} ( )
2020-07-31 13:11:08 -04:00
defer func ( ) {
2023-10-09 12:23:53 -04:00
if err = sl . report ( app , appendTime , time . Since ( start ) , total , added , seriesAdded , bytesRead , scrapeErr ) ; err != nil {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Appending scrape report failed" , "err" , err )
2020-07-31 13:11:08 -04:00
}
} ( )
2020-07-30 08:20:24 -04:00
if forcedErr := sl . getForcedError ( ) ; forcedErr != nil {
2020-07-31 13:11:08 -04:00
scrapeErr = forcedErr
2020-07-30 08:20:24 -04:00
// Add stale markers.
2025-12-22 04:38:48 -05:00
if _ , _ , _ , err := app . append ( [ ] byte { } , "" , appendTime ) ; err != nil {
_ = app . Rollback ( )
app = sl . appender ( )
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Append failed" , "err" , err )
2016-02-22 10:46:55 -05:00
}
2020-07-30 08:20:24 -04:00
if errc != nil {
2025-12-12 08:01:57 -05:00
select {
case errc <- forcedErr :
case <- sl . ctx . Done ( ) :
}
2020-07-30 08:20:24 -04:00
}
2020-07-31 13:11:08 -04:00
return start
}
var contentType string
2023-10-09 12:23:53 -04:00
var resp * http . Response
var b [ ] byte
var buf * bytes . Buffer
2021-10-24 10:38:21 -04:00
scrapeCtx , cancel := context . WithTimeout ( sl . parentCtx , sl . timeout )
2023-10-09 12:23:53 -04:00
resp , scrapeErr = sl . scraper . scrape ( scrapeCtx )
if scrapeErr == nil {
b = sl . buffers . Get ( sl . lastScrapeSize ) . ( [ ] byte )
defer sl . buffers . Put ( b )
buf = bytes . NewBuffer ( b )
contentType , scrapeErr = sl . scraper . readResponse ( scrapeCtx , resp , buf )
}
2020-07-31 13:11:08 -04:00
cancel ( )
if scrapeErr == nil {
b = buf . Bytes ( )
// NOTE: There were issues with misbehaving clients in the past
// that occasionally returned empty results. We don't want those
// to falsely reset our buffer size.
if len ( b ) > 0 {
sl . lastScrapeSize = len ( b )
}
2023-10-09 12:23:53 -04:00
bytesRead = len ( b )
2020-07-30 08:20:24 -04:00
} else {
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Scrape failed" , "err" , scrapeErr )
2024-08-26 05:41:56 -04:00
sl . scrapeFailureLoggerMtx . RLock ( )
if sl . scrapeFailureLogger != nil {
2024-11-23 23:30:23 -05:00
slog . New ( sl . scrapeFailureLogger ) . Error ( scrapeErr . Error ( ) )
2024-08-26 05:41:56 -04:00
}
sl . scrapeFailureLoggerMtx . RUnlock ( )
2020-07-31 13:11:08 -04:00
if errc != nil {
2025-12-12 08:01:57 -05:00
select {
case errc <- scrapeErr :
case <- sl . ctx . Done ( ) :
}
2020-07-30 08:20:24 -04:00
}
2021-10-24 17:45:31 -04:00
if errors . Is ( scrapeErr , errBodySizeLimit ) {
2023-10-09 12:23:53 -04:00
bytesRead = - 1
2021-10-24 17:45:31 -04:00
}
2020-07-31 13:11:08 -04:00
}
2020-07-30 08:20:24 -04:00
2020-07-31 13:11:08 -04:00
// A failed scrape is the same as an empty scrape,
// we still call sl.append to trigger stale markers.
2025-12-22 04:38:48 -05:00
total , added , seriesAdded , appErr = app . append ( b , contentType , appendTime )
2020-07-31 13:11:08 -04:00
if appErr != nil {
2025-12-22 04:38:48 -05:00
_ = app . Rollback ( )
app = sl . appender ( )
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Append failed" , "err" , appErr )
2020-07-31 13:11:08 -04:00
// The append failed, probably due to a parse error or sample limit.
// Call sl.append again with an empty scrape to trigger stale markers.
2025-12-22 04:38:48 -05:00
if _ , _ , _ , err := app . append ( [ ] byte { } , "" , appendTime ) ; err != nil {
_ = app . Rollback ( )
app = sl . appender ( )
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Append failed" , "err" , err )
2020-07-30 08:20:24 -04:00
}
2016-02-22 10:46:55 -05:00
}
2017-05-10 11:59:02 -04:00
2020-07-16 07:53:39 -04:00
if scrapeErr == nil {
scrapeErr = appErr
}
return start
2017-05-16 08:12:21 -04:00
}
2020-07-30 08:20:24 -04:00
func ( sl * scrapeLoop ) setForcedError ( err error ) {
sl . forcedErrMtx . Lock ( )
defer sl . forcedErrMtx . Unlock ( )
sl . forcedErr = err
}
func ( sl * scrapeLoop ) getForcedError ( ) error {
sl . forcedErrMtx . Lock ( )
defer sl . forcedErrMtx . Unlock ( )
return sl . forcedErr
}
2017-05-16 08:12:21 -04:00
func ( sl * scrapeLoop ) endOfRunStaleness ( last time . Time , ticker * time . Ticker , interval time . Duration ) {
2017-05-10 11:59:02 -04:00
// Scraping has stopped. We want to write stale markers but
// the target may be recreated, so we wait just over 2 scrape intervals
// before creating them.
2018-11-27 11:44:29 -05:00
// If the context is canceled, we presume the server is shutting down
2017-05-10 11:59:02 -04:00
// and will restart where is was. We do not attempt to write stale markers
// in this case.
if last . IsZero ( ) {
// There never was a scrape, so there will be no stale markers.
return
}
// Wait for when the next scrape would have been, record its timestamp.
var staleTime time . Time
select {
2019-08-28 09:55:09 -04:00
case <- sl . parentCtx . Done ( ) :
2017-05-10 11:59:02 -04:00
return
case <- ticker . C :
staleTime = time . Now ( )
}
// Wait for when the next scrape would have been, if the target was recreated
// samples should have been ingested by now.
select {
2019-08-28 09:55:09 -04:00
case <- sl . parentCtx . Done ( ) :
2017-05-10 11:59:02 -04:00
return
case <- ticker . C :
}
// Wait for an extra 10% of the interval, just to be safe.
select {
2019-08-28 09:55:09 -04:00
case <- sl . parentCtx . Done ( ) :
2017-05-10 11:59:02 -04:00
return
case <- time . After ( interval / 10 ) :
}
2025-10-30 06:58:31 -04:00
// Check if end-of-run staleness markers have been disabled while we were waiting.
if sl . disabledEndOfRunStalenessMarkers . Load ( ) {
return
}
2017-05-10 11:59:02 -04:00
// Call sl.append again with an empty scrape to trigger stale markers.
// If the target has since been recreated and scraped, the
// stale markers will be out of order and ignored.
2022-05-03 14:45:52 -04:00
// sl.context would have been cancelled, hence using sl.appenderCtx.
2025-12-22 04:38:48 -05:00
app := sl . appender ( )
2020-07-16 07:53:39 -04:00
var err error
defer func ( ) {
if err != nil {
2025-12-22 04:38:48 -05:00
_ = app . Rollback ( )
2020-07-16 07:53:39 -04:00
return
}
err = app . Commit ( )
if err != nil {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Stale commit failed" , "err" , err )
2020-07-16 07:53:39 -04:00
}
} ( )
2025-12-22 04:38:48 -05:00
if _ , _ , _ , err = app . append ( [ ] byte { } , "" , staleTime ) ; err != nil {
_ = app . Rollback ( )
app = sl . appender ( )
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Stale append failed" , "err" , err )
2017-05-10 11:59:02 -04:00
}
2020-07-16 07:53:39 -04:00
if err = sl . reportStale ( app , staleTime ) ; err != nil {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Stale report failed" , "err" , err )
2017-05-11 09:43:43 -04:00
}
2016-02-22 10:46:55 -05:00
}
2017-05-10 11:59:02 -04:00
// Stop the scraping. May still write data and stale markers after it has
// returned. Cancel the context to stop all writes.
2016-02-22 10:46:55 -05:00
func ( sl * scrapeLoop ) stop ( ) {
sl . cancel ( )
2017-05-10 11:59:02 -04:00
<- sl . stopped
2016-02-22 10:46:55 -05:00
}
2020-03-20 12:43:26 -04:00
func ( sl * scrapeLoop ) disableEndOfRunStalenessMarkers ( ) {
2025-10-30 06:58:31 -04:00
sl . disabledEndOfRunStalenessMarkers . Store ( true )
2020-03-20 12:43:26 -04:00
}
2020-01-22 07:13:47 -05:00
func ( sl * scrapeLoop ) getCache ( ) * scrapeCache {
return sl . cache
}
2020-03-25 22:31:48 -04:00
type appendErrors struct {
2023-04-21 15:14:19 -04:00
numOutOfOrder int
numDuplicates int
numOutOfBounds int
numExemplarOutOfOrder int
2020-03-25 22:31:48 -04:00
}
2024-11-07 06:30:03 -05:00
// Update the stale markers.
func ( sl * scrapeLoop ) updateStaleMarkers ( app storage . Appender , defTime int64 ) ( err error ) {
2025-04-14 10:46:53 -04:00
sl . cache . forEachStale ( func ( ref storage . SeriesRef , lset labels . Labels ) bool {
2024-11-07 06:30:03 -05:00
// Series no longer exposed, mark it stale.
2025-12-22 04:38:48 -05:00
app . SetOptions ( & aOptionRejectEarlyOOO )
2025-04-14 10:46:53 -04:00
_ , err = app . Append ( ref , lset , defTime , math . Float64frombits ( value . StaleNaN ) )
2024-11-07 06:30:03 -05:00
app . SetOptions ( nil )
switch {
case errors . Is ( err , storage . ErrOutOfOrderSample ) , errors . Is ( err , storage . ErrDuplicateSampleForTimestamp ) :
// Do not count these in logging, as this is expected if a target
// goes away and comes back again with a new scrape loop.
err = nil
}
return err == nil
} )
2025-11-05 07:47:34 -05:00
return err
2024-11-07 06:30:03 -05:00
}
2025-12-22 04:38:48 -05:00
type scrapeLoopAppender struct {
* scrapeLoop
storage . Appender
}
var _ scrapeLoopAppendAdapter = & scrapeLoopAppender { }
func ( sl * scrapeLoopAppender ) append ( b [ ] byte , contentType string , ts time . Time ) ( total , added , seriesAdded int , err error ) {
2024-11-07 06:30:03 -05:00
defTime := timestamp . FromTime ( ts )
if len ( b ) == 0 {
// Empty scrape. Just update the stale makers and swap the cache (but don't flush it).
2025-12-22 04:38:48 -05:00
err = sl . updateStaleMarkers ( sl . Appender , defTime )
2024-11-07 06:30:03 -05:00
sl . cache . iterDone ( false )
2025-11-05 07:47:34 -05:00
return total , added , seriesAdded , err
2024-11-07 06:30:03 -05:00
}
2025-09-11 05:49:42 -04:00
p , err := textparse . New ( b , contentType , sl . symbolTable , textparse . ParserOptions {
EnableTypeAndUnitLabels : sl . enableTypeAndUnitLabels ,
2025-10-09 10:56:13 -04:00
IgnoreNativeHistograms : ! sl . enableNativeHistogramScraping ,
2025-09-11 05:49:42 -04:00
ConvertClassicHistogramsToNHCB : sl . convertClassicHistToNHCB ,
KeepClassicOnClassicAndNativeHistograms : sl . alwaysScrapeClassicHist ,
2025-11-13 09:17:51 -05:00
OpenMetricsSkipSTSeries : sl . enableSTZeroIngestion ,
2025-09-11 05:49:42 -04:00
FallbackContentType : sl . fallbackScrapeProtocol ,
} )
2024-10-18 11:12:31 -04:00
if p == nil {
sl . l . Error (
"Failed to determine correct type of scrape target." ,
"content_type" , contentType ,
"fallback_media_type" , sl . fallbackScrapeProtocol ,
"err" , err ,
)
2025-11-05 07:47:34 -05:00
return total , added , seriesAdded , err
2024-10-18 11:12:31 -04:00
}
2022-02-08 05:01:37 -05:00
if err != nil {
2024-09-09 21:41:53 -04:00
sl . l . Debug (
2024-10-18 11:12:31 -04:00
"Invalid content type on scrape, using fallback setting." ,
2022-02-08 05:01:37 -05:00
"content_type" , contentType ,
2024-10-18 11:12:31 -04:00
"fallback_media_type" , sl . fallbackScrapeProtocol ,
2022-02-08 05:01:37 -05:00
"err" , err ,
2022-02-08 04:57:56 -05:00
)
}
2016-04-25 10:43:52 -04:00
var (
2025-01-15 06:33:42 -05:00
appErrs = appendErrors { }
sampleLimitErr error
bucketLimitErr error
2025-10-09 10:56:13 -04:00
lset labels . Labels // Escapes to heap so hoisted out of loop.
e exemplar . Exemplar // Escapes to heap so hoisted out of loop.
2025-01-15 06:33:42 -05:00
lastMeta * metaEntry
lastMFName [ ] byte
2016-04-25 10:43:52 -04:00
)
2016-02-22 10:46:55 -05:00
2024-10-10 04:14:40 -04:00
exemplars := make ( [ ] exemplar . Exemplar , 0 , 1 )
2023-11-16 09:07:37 -05:00
2021-12-10 07:03:28 -05:00
// Take an appender with limits.
2025-12-22 04:38:48 -05:00
app := appenderWithLimits ( sl . Appender , sl . sampleLimit , sl . bucketLimit , sl . maxSchema )
2021-12-10 07:03:28 -05:00
2020-03-13 15:54:47 -04:00
defer func ( ) {
if err != nil {
return
}
2024-11-07 06:30:03 -05:00
// Flush and swap the cache as the scrape was non-empty.
sl . cache . iterDone ( true )
2020-03-13 15:54:47 -04:00
} ( )
2017-02-01 09:59:37 -05:00
loop :
2018-05-14 16:19:53 -04:00
for {
2020-03-25 22:31:48 -04:00
var (
2021-06-29 17:45:23 -04:00
et textparse . Entry
sampleAdded , isHistogram bool
met [ ] byte
parsedTimestamp * int64
val float64
2021-11-12 13:07:41 -05:00
h * histogram . Histogram
2022-12-28 03:55:07 -05:00
fh * histogram . FloatHistogram
2020-03-25 22:31:48 -04:00
)
2018-05-14 16:19:53 -04:00
if et , err = p . Next ( ) ; err != nil {
2022-12-29 10:23:07 -05:00
if errors . Is ( err , io . EOF ) {
2018-05-14 16:19:53 -04:00
err = nil
}
break
}
2018-05-18 03:32:11 -04:00
switch et {
2026-01-21 03:21:56 -05:00
// TODO(bwplotka): Consider changing parser to give metadata at once instead of type, help and unit in separation, ideally on `Series()/Histogram()`
2025-01-15 06:33:42 -05:00
// otherwise we can expose metadata without series on metadata API.
2018-05-18 03:32:11 -04:00
case textparse . EntryType :
2025-01-15 06:33:42 -05:00
// TODO(bwplotka): Build meta entry directly instead of locking and updating the map. This will
// allow to properly update metadata when e.g unit was added, then removed;
lastMFName , lastMeta = sl . cache . setType ( p . Type ( ) )
2018-05-18 03:32:11 -04:00
continue
case textparse . EntryHelp :
2025-01-15 06:33:42 -05:00
lastMFName , lastMeta = sl . cache . setHelp ( p . Help ( ) )
2018-05-14 16:19:53 -04:00
continue
2018-10-05 12:11:16 -04:00
case textparse . EntryUnit :
2025-01-15 06:33:42 -05:00
lastMFName , lastMeta = sl . cache . setUnit ( p . Unit ( ) )
2018-10-05 12:11:16 -04:00
continue
2018-05-18 03:32:11 -04:00
case textparse . EntryComment :
continue
2021-06-29 17:45:23 -04:00
case textparse . EntryHistogram :
isHistogram = true
2018-05-18 03:32:11 -04:00
default :
2018-05-14 16:19:53 -04:00
}
2017-01-30 11:30:28 -05:00
total ++
2017-01-15 11:33:07 -05:00
t := defTime
2021-06-29 17:45:23 -04:00
if isHistogram {
2022-12-28 03:55:07 -05:00
met , parsedTimestamp , h , fh = p . Histogram ( )
2021-06-29 17:45:23 -04:00
} else {
met , parsedTimestamp , val = p . Series ( )
}
2019-03-15 06:04:15 -04:00
if ! sl . honorTimestamps {
2021-06-29 17:45:23 -04:00
parsedTimestamp = nil
2019-03-15 06:04:15 -04:00
}
2021-06-29 17:45:23 -04:00
if parsedTimestamp != nil {
t = * parsedTimestamp
2017-01-15 11:33:07 -05:00
}
2025-10-09 10:56:13 -04:00
if sl . cache . getDropped ( met ) {
2017-09-08 08:34:45 -04:00
continue
}
2025-01-16 08:15:56 -05:00
ce , seriesCached , seriesAlreadyScraped := sl . cache . get ( met )
2021-02-18 07:07:00 -05:00
var (
2021-11-06 06:10:04 -04:00
ref storage . SeriesRef
2021-02-18 07:07:00 -05:00
hash uint64
)
2020-03-25 22:31:48 -04:00
2025-01-16 08:15:56 -05:00
if seriesCached {
2021-02-18 07:07:00 -05:00
ref = ce . ref
lset = ce . lset
2023-11-16 08:22:28 -05:00
hash = ce . hash
2021-02-18 07:07:00 -05:00
} else {
2025-02-12 10:47:56 -05:00
p . Labels ( & lset )
2021-02-18 07:07:00 -05:00
hash = lset . Hash ( )
2017-09-15 05:08:51 -04:00
// Hash label set as it is seen local to the target. Then add target labels
// and relabeling and store the final label set.
lset = sl . sampleMutator ( lset )
2022-03-09 17:26:24 -05:00
// The label set may be set to empty to indicate dropping.
if lset . IsEmpty ( ) {
2023-01-04 07:05:42 -05:00
sl . cache . addDropped ( met )
2017-09-15 05:08:51 -04:00
continue
2017-06-26 02:56:40 -04:00
}
2017-01-30 11:30:28 -05:00
2025-12-22 04:38:48 -05:00
if ! lset . Has ( model . MetricNameLabel ) {
2020-03-02 02:18:05 -05:00
err = errNameLabelMandatory
break loop
}
2024-08-28 11:15:42 -04:00
if ! lset . IsValid ( sl . validationScheme ) {
2022-12-07 22:09:43 -05:00
err = fmt . Errorf ( "invalid metric name or label names: %s" , lset . String ( ) )
break loop
}
2021-05-06 04:56:21 -04:00
// If any label limits is exceeded the scrape should fail.
if err = verifyLabelLimits ( lset , sl . labelLimits ) ; err != nil {
2023-09-22 12:47:44 -04:00
sl . metrics . targetScrapePoolExceededLabelLimits . Inc ( )
2021-05-06 04:56:21 -04:00
break loop
}
2021-02-18 07:07:00 -05:00
}
2020-03-02 02:18:05 -05:00
2024-08-19 05:58:35 -04:00
if seriesAlreadyScraped && parsedTimestamp == nil {
2023-11-16 08:22:28 -05:00
err = storage . ErrDuplicateSampleForTimestamp
} else {
2025-11-13 09:17:51 -05:00
if sl . enableSTZeroIngestion {
if stMs := p . StartTimestamp ( ) ; stMs != 0 {
2025-03-17 09:07:07 -04:00
if isHistogram {
2024-07-19 10:28:00 -04:00
if h != nil {
2025-11-13 09:17:51 -05:00
ref , err = app . AppendHistogramSTZeroSample ( ref , lset , t , stMs , h , nil )
2024-07-19 10:28:00 -04:00
} else {
2025-11-13 09:17:51 -05:00
ref , err = app . AppendHistogramSTZeroSample ( ref , lset , t , stMs , nil , fh )
2024-07-19 10:28:00 -04:00
}
} else {
2025-11-13 09:17:51 -05:00
ref , err = app . AppendSTZeroSample ( ref , lset , t , stMs )
2024-07-19 10:28:00 -04:00
}
2025-11-13 09:17:51 -05:00
if err != nil && ! errors . Is ( err , storage . ErrOutOfOrderST ) { // OOO is a common case, ignoring completely for now.
// ST is an experimental feature. For now, we don't need to fail the
2024-09-03 02:33:44 -04:00
// scrape on errors updating the created timestamp, log debug.
2025-11-13 09:17:51 -05:00
sl . l . Debug ( "Error when appending ST in scrape loop" , "series" , string ( met ) , "ct" , stMs , "t" , t , "err" , err )
2024-09-03 02:33:44 -04:00
}
2023-11-16 08:22:28 -05:00
}
2023-12-11 03:43:42 -05:00
}
2025-03-17 09:07:07 -04:00
if isHistogram {
2023-11-16 08:22:28 -05:00
if h != nil {
ref , err = app . AppendHistogram ( ref , lset , t , h , nil )
} else {
ref , err = app . AppendHistogram ( ref , lset , t , nil , fh )
}
2022-12-28 03:55:07 -05:00
} else {
2024-07-03 05:56:48 -04:00
ref , err = app . Append ( ref , lset , t , val )
2022-08-25 11:07:41 -04:00
}
2021-06-29 17:45:23 -04:00
}
2023-11-16 08:22:28 -05:00
2023-11-28 12:42:29 -05:00
if err == nil {
if ( parsedTimestamp == nil || sl . trackTimestampsStaleness ) && ce != nil {
2025-09-02 10:17:24 -04:00
sl . cache . trackStaleness ( ce . ref , ce )
2023-11-28 12:42:29 -05:00
}
}
2026-01-21 03:21:56 -05:00
sampleAdded , err = sl . checkAddError ( met , nil , err , & sampleLimitErr , & bucketLimitErr , & appErrs )
2021-02-18 07:07:00 -05:00
if err != nil {
2023-11-01 15:06:46 -04:00
if ! errors . Is ( err , storage . ErrNotFound ) {
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Unexpected error" , "series" , string ( met ) , "err" , err )
2016-02-22 10:46:55 -05:00
}
2021-02-18 07:07:00 -05:00
break loop
}
2020-03-25 22:31:48 -04:00
2025-04-28 11:05:37 -04:00
// If series wasn't cached (is new, not seen on previous scrape) we need need to add it to the scrape cache.
// But we only do this for series that were appended to TSDB without errors.
// If a series was new but we didn't append it due to sample_limit or other errors then we don't need
// it in the scrape cache because we don't need to emit StaleNaNs for it when it disappears.
if ! seriesCached && sampleAdded {
2025-04-14 10:46:53 -04:00
ce = sl . cache . addRef ( met , ref , lset , hash )
2025-04-29 04:24:27 -04:00
if ce != nil && ( parsedTimestamp == nil || sl . trackTimestampsStaleness ) {
2017-04-28 11:36:36 -04:00
// Bypass staleness logic if there is an explicit timestamp.
2025-04-29 04:24:27 -04:00
// But make sure we only do this if we have a cache entry (ce) for our series.
2025-09-02 10:17:24 -04:00
sl . cache . trackStaleness ( ref , ce )
2017-04-28 11:36:36 -04:00
}
2025-12-22 04:38:48 -05:00
if sampleLimitErr == nil && bucketLimitErr == nil {
2020-03-25 22:31:48 -04:00
seriesAdded ++
}
}
2020-06-04 11:00:37 -04:00
// Increment added even if there's an error so we correctly report the
2020-07-11 09:37:13 -04:00
// number of samples remaining after relabeling.
2023-11-16 08:22:28 -05:00
// We still report duplicated samples here since this number should be the exact number
// of time series exposed on a scrape after relabelling.
2020-06-04 11:00:37 -04:00
added ++
2023-11-16 09:07:37 -05:00
exemplars = exemplars [ : 0 ] // Reset and reuse the exemplar slice.
2023-07-13 08:16:10 -04:00
for hasExemplar := p . Exemplar ( & e ) ; hasExemplar ; hasExemplar = p . Exemplar ( & e ) {
2021-03-16 05:47:45 -04:00
if ! e . HasTs {
2023-11-16 09:07:37 -05:00
if isHistogram {
// We drop exemplars for native histograms if they don't have a timestamp.
// Missing timestamps are deliberately not supported as we want to start
// enforcing timestamps for exemplars as otherwise proper deduplication
// is inefficient and purely based on heuristics: we cannot distinguish
// between repeated exemplars and new instances with the same values.
// This is done silently without logs as it is not an error but out of spec.
// This does not affect classic histograms so that behaviour is unchanged.
e = exemplar . Exemplar { } // Reset for next time round loop.
continue
}
2021-03-16 05:47:45 -04:00
e . Ts = t
}
2023-11-16 09:07:37 -05:00
exemplars = append ( exemplars , e )
e = exemplar . Exemplar { } // Reset for next time round loop.
}
2023-11-24 09:38:35 -05:00
// Sort so that checking for duplicates / out of order is more efficient during validation.
slices . SortFunc ( exemplars , exemplar . Compare )
2023-11-16 09:07:37 -05:00
outOfOrderExemplars := 0
for _ , e := range exemplars {
2021-03-16 05:47:45 -04:00
_ , exemplarErr := app . AppendExemplar ( ref , lset , e )
2023-11-16 09:07:37 -05:00
switch {
case exemplarErr == nil :
// Do nothing.
case errors . Is ( exemplarErr , storage . ErrOutOfOrderExemplar ) :
outOfOrderExemplars ++
default :
2021-03-16 05:47:45 -04:00
// Since exemplar storage is still experimental, we don't fail the scrape on ingestion errors.
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Error while adding exemplar in AddExemplar" , "exemplar" , fmt . Sprintf ( "%+v" , e ) , "err" , exemplarErr )
2021-03-16 05:47:45 -04:00
}
2023-11-16 09:07:37 -05:00
}
if outOfOrderExemplars > 0 && outOfOrderExemplars == len ( exemplars ) {
// Only report out of order exemplars if all are out of order, otherwise this was a partial update
// to some existing set of exemplars.
appErrs . numExemplarOutOfOrder += outOfOrderExemplars
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Out of order exemplars" , "count" , outOfOrderExemplars , "latest" , fmt . Sprintf ( "%+v" , exemplars [ len ( exemplars ) - 1 ] ) )
2023-11-16 09:07:37 -05:00
sl . metrics . targetScrapeExemplarOutOfOrder . Add ( float64 ( outOfOrderExemplars ) )
2021-03-16 05:47:45 -04:00
}
2025-01-15 06:33:42 -05:00
if sl . appendMetadataToWAL && lastMeta != nil {
// Is it new series OR did metadata change for this family?
2025-01-16 08:15:56 -05:00
if ! seriesCached || lastMeta . lastIterChange == sl . cache . iter {
2025-01-15 06:33:42 -05:00
// In majority cases we can trust that the current series/histogram is matching the lastMeta and lastMFName.
// However, optional TYPE etc metadata and broken OM text can break this, detect those cases here.
2026-01-21 03:21:56 -05:00
// TODO(https://github.com/prometheus/prometheus/issues/17900): Move this to text and OM parser.
2025-12-22 04:38:48 -05:00
if isSeriesPartOfFamily ( lset . Get ( model . MetricNameLabel ) , lastMFName , lastMeta . Type ) {
2025-01-15 06:33:42 -05:00
if _ , merr := app . UpdateMetadata ( ref , lset , lastMeta . Metadata ) ; merr != nil {
// No need to fail the scrape on errors appending metadata.
sl . l . Debug ( "Error when appending metadata in scrape loop" , "ref" , fmt . Sprintf ( "%d" , ref ) , "metadata" , fmt . Sprintf ( "%+v" , lastMeta . Metadata ) , "err" , merr )
}
}
2022-08-31 09:50:05 -04:00
}
}
2016-02-22 10:46:55 -05:00
}
2018-01-09 10:43:28 -05:00
if sampleLimitErr != nil {
2018-05-14 16:19:53 -04:00
if err == nil {
err = sampleLimitErr
}
2018-01-09 10:43:28 -05:00
// We only want to increment this once per scrape, so this is Inc'd outside the loop.
2023-09-22 12:47:44 -04:00
sl . metrics . targetScrapeSampleLimit . Inc ( )
2017-05-29 09:08:55 -04:00
}
2023-04-21 15:14:19 -04:00
if bucketLimitErr != nil {
if err == nil {
2023-05-04 14:29:50 -04:00
err = bucketLimitErr // If sample limit is hit, that error takes precedence.
2023-04-21 15:14:19 -04:00
}
// We only want to increment this once per scrape, so this is Inc'd outside the loop.
2023-09-22 12:47:44 -04:00
sl . metrics . targetScrapeNativeHistogramBucketLimit . Inc ( )
2023-04-21 15:14:19 -04:00
}
2020-03-25 22:31:48 -04:00
if appErrs . numOutOfOrder > 0 {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Error on ingesting out-of-order samples" , "num_dropped" , appErrs . numOutOfOrder )
2017-05-16 08:30:40 -04:00
}
2020-03-25 22:31:48 -04:00
if appErrs . numDuplicates > 0 {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Error on ingesting samples with different value but same timestamp" , "num_dropped" , appErrs . numDuplicates )
2017-05-16 08:30:40 -04:00
}
2020-03-25 22:31:48 -04:00
if appErrs . numOutOfBounds > 0 {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Error on ingesting samples that are too old or are too far into the future" , "num_dropped" , appErrs . numOutOfBounds )
2017-07-04 05:24:13 -04:00
}
2021-03-16 05:47:45 -04:00
if appErrs . numExemplarOutOfOrder > 0 {
2024-09-09 21:41:53 -04:00
sl . l . Warn ( "Error on ingesting out-of-order exemplars" , "num_dropped" , appErrs . numExemplarOutOfOrder )
2021-03-16 05:47:45 -04:00
}
2017-04-13 13:07:23 -04:00
if err == nil {
2024-11-07 06:30:03 -05:00
err = sl . updateStaleMarkers ( app , defTime )
2017-04-13 13:07:23 -04:00
}
2025-11-05 07:47:34 -05:00
return total , added , seriesAdded , err
2016-02-22 10:46:55 -05:00
}
2026-01-21 03:21:56 -05:00
// TODO(https://github.com/prometheus/prometheus/issues/17900): Move this to text and OM parser.
2025-01-15 06:33:42 -05:00
func isSeriesPartOfFamily ( mName string , mfName [ ] byte , typ model . MetricType ) bool {
mfNameStr := yoloString ( mfName )
if ! strings . HasPrefix ( mName , mfNameStr ) { // Fast path.
return false
}
var (
gotMFName string
ok bool
)
switch typ {
case model . MetricTypeCounter :
// Prometheus allows _total, cut it from mf name to support this case.
mfNameStr , _ = strings . CutSuffix ( mfNameStr , "_total" )
gotMFName , ok = strings . CutSuffix ( mName , "_total" )
if ! ok {
gotMFName = mName
}
case model . MetricTypeHistogram :
gotMFName , ok = strings . CutSuffix ( mName , "_bucket" )
if ! ok {
gotMFName , ok = strings . CutSuffix ( mName , "_sum" )
if ! ok {
gotMFName , ok = strings . CutSuffix ( mName , "_count" )
if ! ok {
gotMFName = mName
}
}
}
case model . MetricTypeGaugeHistogram :
gotMFName , ok = strings . CutSuffix ( mName , "_bucket" )
if ! ok {
gotMFName , ok = strings . CutSuffix ( mName , "_gsum" )
if ! ok {
gotMFName , ok = strings . CutSuffix ( mName , "_gcount" )
if ! ok {
gotMFName = mName
}
}
}
case model . MetricTypeSummary :
gotMFName , ok = strings . CutSuffix ( mName , "_sum" )
if ! ok {
gotMFName , ok = strings . CutSuffix ( mName , "_count" )
if ! ok {
gotMFName = mName
}
}
case model . MetricTypeInfo :
// Technically prometheus text does not support info type, but we might
// accidentally allow info type in prom parse, so support metric family names
// with the _info explicitly too.
mfNameStr , _ = strings . CutSuffix ( mfNameStr , "_info" )
gotMFName , ok = strings . CutSuffix ( mName , "_info" )
if ! ok {
gotMFName = mName
}
default :
gotMFName = mName
}
return mfNameStr == gotMFName
}
2020-03-25 22:31:48 -04:00
// Adds samples to the appender, checking the error, and then returns the # of samples added,
2023-04-21 15:14:19 -04:00
// whether the caller should continue to process more samples, and any sample or bucket limit errors.
2025-02-13 08:25:50 -05:00
// Switch error cases for Sample and Bucket limits are checked first since they're more common
// during normal operation (e.g., accidental cardinality explosion, sudden traffic spikes).
// Current case ordering prevents exercising other cases when limits are exceeded.
// Remaining error cases typically occur only a few times, often during initial setup.
2026-01-21 03:21:56 -05:00
func ( sl * scrapeLoop ) checkAddError ( met [ ] byte , exemplars [ ] exemplar . Exemplar , err error , sampleLimitErr , bucketLimitErr * error , appErrs * appendErrors ) ( sampleAdded bool , _ error ) {
2023-11-01 15:06:46 -04:00
switch {
case err == nil :
2020-03-25 22:31:48 -04:00
return true , nil
2025-02-13 08:25:50 -05:00
case errors . Is ( err , errSampleLimit ) :
// Keep on parsing output if we hit the limit, so we report the correct
// total number of samples scraped.
* sampleLimitErr = err
return false , nil
case errors . Is ( err , errBucketLimit ) :
// Keep on parsing output if we hit the limit, so we report the bucket
// total number of samples scraped.
* bucketLimitErr = err
return false , nil
2023-11-01 15:06:46 -04:00
case errors . Is ( err , storage . ErrOutOfOrderSample ) :
2020-03-25 22:31:48 -04:00
appErrs . numOutOfOrder ++
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Out of order sample" , "series" , string ( met ) )
2023-09-22 12:47:44 -04:00
sl . metrics . targetScrapeSampleOutOfOrder . Inc ( )
2020-03-25 22:31:48 -04:00
return false , nil
2023-11-01 15:06:46 -04:00
case errors . Is ( err , storage . ErrDuplicateSampleForTimestamp ) :
2020-03-25 22:31:48 -04:00
appErrs . numDuplicates ++
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Duplicate sample for timestamp" , "series" , string ( met ) )
2023-09-22 12:47:44 -04:00
sl . metrics . targetScrapeSampleDuplicate . Inc ( )
2020-03-25 22:31:48 -04:00
return false , nil
2023-11-01 15:06:46 -04:00
case errors . Is ( err , storage . ErrOutOfBounds ) :
2020-03-25 22:31:48 -04:00
appErrs . numOutOfBounds ++
2024-09-09 21:41:53 -04:00
sl . l . Debug ( "Out of bounds metric" , "series" , string ( met ) )
2023-09-22 12:47:44 -04:00
sl . metrics . targetScrapeSampleOutOfBounds . Inc ( )
2020-03-25 22:31:48 -04:00
return false , nil
2025-02-13 08:25:50 -05:00
case errors . Is ( err , storage . ErrNotFound ) :
return false , storage . ErrNotFound
2020-03-25 22:31:48 -04:00
default :
2026-01-21 03:21:56 -05:00
// If nothing from the above, check for partial errors. Do this here to not alloc the pErr on a hot path.
var pErr * storage . AppendPartialError
if errors . As ( err , & pErr ) {
outOfOrderExemplars := 0
for _ , e := range pErr . ExemplarErrors {
if errors . Is ( e , storage . ErrOutOfOrderExemplar ) {
outOfOrderExemplars ++
}
// Since exemplar storage is still experimental, we don't fail or check other errors.
// Debug log is emitted in TSDB already.
}
if outOfOrderExemplars > 0 && outOfOrderExemplars == len ( exemplars ) {
// Only report out of order exemplars if all are out of order, otherwise this was a partial update
// to some existing set of exemplars.
appErrs . numExemplarOutOfOrder += outOfOrderExemplars
sl . l . Debug ( "Out of order exemplars" , "count" , outOfOrderExemplars , "latest" , fmt . Sprintf ( "%+v" , exemplars [ len ( exemplars ) - 1 ] ) )
sl . metrics . targetScrapeExemplarOutOfOrder . Add ( float64 ( outOfOrderExemplars ) )
}
return true , nil
}
2020-03-25 22:31:48 -04:00
return false , err
}
}
2025-01-16 14:47:32 -05:00
// reportSample represents automatically generated timeseries documented in
// https://prometheus.io/docs/concepts/jobs_instances/#automatically-generated-labels-and-time-series
type reportSample struct {
metadata . Metadata
name [ ] byte
}
2017-09-15 05:08:51 -04:00
// The constants are suffixed with the invalid \xff unicode rune to avoid collisions
// with scraped metrics in the cache.
2022-12-20 11:54:07 -05:00
var (
2025-01-16 14:47:32 -05:00
scrapeHealthMetric = reportSample {
name : [ ] byte ( "up" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "Health of the scrape target. 1 means the target is healthy, 0 if the scrape failed." ,
Unit : "targets" ,
} ,
}
scrapeDurationMetric = reportSample {
name : [ ] byte ( "scrape_duration_seconds" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "Duration of the last scrape in seconds." ,
Unit : "seconds" ,
} ,
}
scrapeSamplesMetric = reportSample {
name : [ ] byte ( "scrape_samples_scraped" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "Number of samples last scraped." ,
Unit : "samples" ,
} ,
}
samplesPostRelabelMetric = reportSample {
name : [ ] byte ( "scrape_samples_post_metric_relabeling" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "Number of samples remaining after metric relabeling was applied." ,
Unit : "samples" ,
} ,
}
scrapeSeriesAddedMetric = reportSample {
name : [ ] byte ( "scrape_series_added" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "Number of series in the last scrape." ,
Unit : "series" ,
} ,
}
scrapeTimeoutMetric = reportSample {
name : [ ] byte ( "scrape_timeout_seconds" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "The configured scrape timeout for a target." ,
Unit : "seconds" ,
} ,
}
scrapeSampleLimitMetric = reportSample {
name : [ ] byte ( "scrape_sample_limit" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
Help : "The configured sample limit for a target. Returns zero if there is no limit configured." ,
Unit : "samples" ,
} ,
}
scrapeBodySizeBytesMetric = reportSample {
name : [ ] byte ( "scrape_body_size_bytes" + "\xff" ) ,
Metadata : metadata . Metadata {
Type : model . MetricTypeGauge ,
2025-01-17 04:09:28 -05:00
Help : "The uncompressed size of the last scrape response, if successful. Scrapes failing because body_size_limit is exceeded report -1, other scrape failures report 0." ,
2025-01-16 14:47:32 -05:00
Unit : "bytes" ,
} ,
}
2017-09-15 05:08:51 -04:00
)
2025-12-22 04:38:48 -05:00
func ( sl * scrapeLoop ) report ( app scrapeLoopAppendAdapter , start time . Time , duration time . Duration , scraped , added , seriesAdded , bytes int , scrapeErr error ) ( err error ) {
2020-03-13 15:54:47 -04:00
sl . scraper . Report ( start , duration , scrapeErr )
2016-02-22 10:46:55 -05:00
2017-01-15 11:33:07 -05:00
ts := timestamp . FromTime ( start )
2016-02-22 10:46:55 -05:00
2016-12-29 03:27:30 -05:00
var health float64
2020-03-13 15:54:47 -04:00
if scrapeErr == nil {
2016-02-22 10:46:55 -05:00
health = 1
}
2023-10-10 16:30:19 -04:00
b := labels . NewBuilderWithSymbolTable ( sl . symbolTable )
2017-01-13 08:48:01 -05:00
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeHealthMetric , ts , health , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2017-01-13 08:48:01 -05:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeDurationMetric , ts , duration . Seconds ( ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2016-05-19 10:22:49 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeSamplesMetric , ts , float64 ( scraped ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2016-10-26 12:43:01 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( samplesPostRelabelMetric , ts , float64 ( added ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2017-01-15 11:33:07 -05:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeSeriesAddedMetric , ts , float64 ( seriesAdded ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2019-05-08 17:24:00 -04:00
}
2021-10-24 17:45:31 -04:00
if sl . reportExtraMetrics {
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeTimeoutMetric , ts , sl . timeout . Seconds ( ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2021-08-24 08:31:14 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeSampleLimitMetric , ts , float64 ( sl . sampleLimit ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2021-09-03 09:37:42 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeBodySizeBytesMetric , ts , float64 ( bytes ) , b , false ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2021-10-24 17:45:31 -04:00
}
2021-08-24 08:31:14 -04:00
}
2025-11-05 07:47:34 -05:00
return err
2017-01-15 11:33:07 -05:00
}
2025-12-22 04:38:48 -05:00
func ( sl * scrapeLoop ) reportStale ( app scrapeLoopAppendAdapter , start time . Time ) ( err error ) {
2017-05-11 09:43:43 -04:00
ts := timestamp . FromTime ( start )
stale := math . Float64frombits ( value . StaleNaN )
2023-10-10 16:30:19 -04:00
b := labels . NewBuilder ( labels . EmptyLabels ( ) )
2017-05-11 09:43:43 -04:00
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeHealthMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2017-05-11 09:43:43 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeDurationMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2017-05-11 09:43:43 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeSamplesMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2017-05-11 09:43:43 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( samplesPostRelabelMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2017-05-11 09:43:43 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeSeriesAddedMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2019-05-08 17:24:00 -04:00
}
2021-10-24 17:45:31 -04:00
if sl . reportExtraMetrics {
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeTimeoutMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2021-08-24 08:31:14 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeSampleLimitMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2021-09-03 09:37:42 -04:00
}
2025-12-22 04:38:48 -05:00
if err = app . addReportSample ( scrapeBodySizeBytesMetric , ts , stale , b , true ) ; err != nil {
2025-11-05 07:47:34 -05:00
return err
2021-10-24 17:45:31 -04:00
}
2021-08-24 08:31:14 -04:00
}
2025-11-05 07:47:34 -05:00
return err
2017-05-11 09:43:43 -04:00
}
2025-12-22 04:38:48 -05:00
func ( sl * scrapeLoopAppender ) addReportSample ( s reportSample , t int64 , v float64 , b * labels . Builder , rejectOOO bool ) ( err error ) {
2025-01-16 14:47:32 -05:00
ce , ok , _ := sl . cache . get ( s . name )
2021-11-06 06:10:04 -04:00
var ref storage . SeriesRef
2021-02-18 07:07:00 -05:00
var lset labels . Labels
2017-01-15 11:33:07 -05:00
if ok {
2021-02-18 07:07:00 -05:00
ref = ce . ref
lset = ce . lset
} else {
2022-03-09 17:26:24 -05:00
// The constants are suffixed with the invalid \xff unicode rune to avoid collisions
// with scraped metrics in the cache.
// We have to drop it when building the actual metric.
2023-10-10 16:30:19 -04:00
b . Reset ( labels . EmptyLabels ( ) )
2025-12-22 04:38:48 -05:00
b . Set ( model . MetricNameLabel , string ( s . name [ : len ( s . name ) - 1 ] ) )
2023-10-10 16:30:19 -04:00
lset = sl . reportSampleMutator ( b . Labels ( ) )
2017-01-13 08:48:01 -05:00
}
2017-09-08 08:34:45 -04:00
2025-12-22 04:38:48 -05:00
// This will be improved in AppenderV2.
if rejectOOO {
sl . SetOptions ( & aOptionRejectEarlyOOO )
ref , err = sl . Append ( ref , lset , t , v )
sl . SetOptions ( nil )
} else {
ref , err = sl . Append ( ref , lset , t , v )
}
2023-11-01 15:06:46 -04:00
switch {
case err == nil :
2021-02-18 07:07:00 -05:00
if ! ok {
2025-01-16 14:47:32 -05:00
sl . cache . addRef ( s . name , ref , lset , lset . Hash ( ) )
// We only need to add metadata once a scrape target appears.
if sl . appendMetadataToWAL {
2025-12-22 04:38:48 -05:00
if _ , merr := sl . UpdateMetadata ( ref , lset , s . Metadata ) ; merr != nil {
2025-01-16 14:47:32 -05:00
sl . l . Debug ( "Error when appending metadata in addReportSample" , "ref" , fmt . Sprintf ( "%d" , ref ) , "metadata" , fmt . Sprintf ( "%+v" , s . Metadata ) , "err" , merr )
}
}
2021-02-18 07:07:00 -05:00
}
2017-05-11 09:43:43 -04:00
return nil
2023-11-01 15:06:46 -04:00
case errors . Is ( err , storage . ErrOutOfOrderSample ) , errors . Is ( err , storage . ErrDuplicateSampleForTimestamp ) :
2021-02-18 07:07:00 -05:00
// Do not log here, as this is expected if a target goes away and comes back
// again with a new scrape loop.
2017-05-11 09:43:43 -04:00
return nil
default :
2017-01-15 11:33:07 -05:00
return err
2017-01-13 08:48:01 -05:00
}
2016-02-22 10:46:55 -05:00
}
2020-01-22 07:13:47 -05:00
// zeroConfig returns a new scrape config that only contains configuration items
// that alter metrics.
func zeroConfig ( c * config . ScrapeConfig ) * config . ScrapeConfig {
z := * c
// We zero out the fields that for sure don't affect scrape.
z . ScrapeInterval = 0
z . ScrapeTimeout = 0
z . SampleLimit = 0
z . HTTPClientConfig = config_util . HTTPClientConfig { }
return & z
}
2020-03-02 03:21:24 -05:00
// reusableCache compares two scrape config and tells whether the cache is still
2020-01-22 07:13:47 -05:00
// valid.
func reusableCache ( r , l * config . ScrapeConfig ) bool {
if r == nil || l == nil {
return false
}
return reflect . DeepEqual ( zeroConfig ( r ) , zeroConfig ( l ) )
}
2022-03-16 04:45:15 -04:00
// CtxKey is a dedicated type for keys of context-embedded values propagated
// with the scrape context.
type ctxKey int
// Valid CtxKey values.
const (
ctxKeyMetadata ctxKey = iota + 1
2022-03-24 11:53:04 -04:00
ctxKeyTarget
2022-03-16 04:45:15 -04:00
)
func ContextWithMetricMetadataStore ( ctx context . Context , s MetricMetadataStore ) context . Context {
return context . WithValue ( ctx , ctxKeyMetadata , s )
}
func MetricMetadataStoreFromContext ( ctx context . Context ) ( MetricMetadataStore , bool ) {
s , ok := ctx . Value ( ctxKeyMetadata ) . ( MetricMetadataStore )
return s , ok
}
2022-03-24 11:53:04 -04:00
func ContextWithTarget ( ctx context . Context , t * Target ) context . Context {
return context . WithValue ( ctx , ctxKeyTarget , t )
}
func TargetFromContext ( ctx context . Context ) ( * Target , bool ) {
t , ok := ctx . Value ( ctxKeyTarget ) . ( * Target )
return t , ok
}
2024-01-17 10:58:54 -05:00
func pickSchema ( bucketFactor float64 ) int32 {
if bucketFactor <= 1 {
bucketFactor = 1.00271
}
floor := math . Floor ( - math . Log2 ( math . Log2 ( bucketFactor ) ) )
switch {
2024-02-28 08:06:43 -05:00
case floor >= float64 ( histogram . ExponentialSchemaMax ) :
return histogram . ExponentialSchemaMax
case floor <= float64 ( histogram . ExponentialSchemaMin ) :
return histogram . ExponentialSchemaMin
2024-01-17 10:58:54 -05:00
default :
return int32 ( floor )
}
}
2025-07-15 03:37:24 -04:00
func newScrapeClient ( cfg config_util . HTTPClientConfig , name string , optFuncs ... config_util . HTTPClientOption ) ( * http . Client , error ) {
client , err := config_util . NewClientFromConfig ( cfg , name , optFuncs ... )
if err != nil {
return nil , fmt . Errorf ( "error creating HTTP client: %w" , err )
}
client . Transport = otelhttp . NewTransport (
client . Transport ,
otelhttp . WithClientTrace ( func ( ctx context . Context ) * httptrace . ClientTrace {
return otelhttptrace . NewClientTrace ( ctx , otelhttptrace . WithoutSubSpans ( ) )
} ) )
return client , nil
}