Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* [FEATURE] Distributor: Add experimental OTLP metrics ingestion over gRPC (`opentelemetry.proto.collector.metrics.v1.MetricsService/Export`) on the gRPC server port. Enable it with `-distributor.otlp.grpc-enabled`. The tenant is read from the `X-Scope-OrgID` gRPC metadata, and the request size is limited by `-server.grpc-max-recv-msg-size-bytes`. #7873
* [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-<prefix>.oss.*` flags with `backend: oss`. #7907
* [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916
* [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #7973
* [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910
* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits` (requires zone-aware replication). It converts global series and metadata limits to per-ingester limits using the ingester's actual share of each tenant's hash space within its zone, instead of an equal share, which throttles tenants early on an unbalanced ring. Shares ignore `-distributor.extend-writes`, so a tenant can be throttled early while an instance is JOINING, LEAVING or PENDING. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961
* [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761
Expand Down
11 changes: 11 additions & 0 deletions docs/blocks-storage/compactor.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ compactor:
# CLI flag: -compactor.compaction-concurrency
[compaction_concurrency: <int> | default = 1]

# How long to let a compaction that is already running finish once shutdown
# has been requested, before cancelling it. As soon as shutdown is requested
# the compactor stops planning new compaction groups and stops picking up
# further tenants, regardless of this setting. 0 cancels the running
# compaction immediately, discarding the work it has done so far. A compaction
# is only allowed to finish if the process is given at least this long to
# terminate, so this value should be below the deployment's termination grace
# period.
# CLI flag: -compactor.compaction-drain-timeout
[compaction_drain_timeout: <duration> | default = 0s]

# How frequently compactor should run blocks cleanup and maintenance, as well
# as update the bucket index.
# CLI flag: -compactor.cleanup-interval
Expand Down
10 changes: 10 additions & 0 deletions docs/configuration/config-file-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3146,6 +3146,16 @@ The `compactor_config` configures the compactor for the blocks storage.
# CLI flag: -compactor.compaction-concurrency
[compaction_concurrency: <int> | default = 1]

# How long to let a compaction that is already running finish once shutdown has
# been requested, before cancelling it. As soon as shutdown is requested the
# compactor stops planning new compaction groups and stops picking up further
# tenants, regardless of this setting. 0 cancels the running compaction
# immediately, discarding the work it has done so far. A compaction is only
# allowed to finish if the process is given at least this long to terminate, so
# this value should be below the deployment's termination grace period.
# CLI flag: -compactor.compaction-drain-timeout
[compaction_drain_timeout: <duration> | default = 0s]

# How frequently compactor should run blocks cleanup and maintenance, as well as
# update the bucket index.
# CLI flag: -compactor.cleanup-interval
Expand Down
114 changes: 99 additions & 15 deletions pkg/compactor/compactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ var (
supportedShardingStrategies = []string{util.ShardingStrategyDefault, util.ShardingStrategyShuffle}
errInvalidShardingStrategy = errors.New("invalid sharding strategy")
errInvalidBlockMergeFanIn = errors.New("invalid block merge fan-in, the value must not be negative")
errInvalidCompactionDrainTimeout = errors.New("invalid compaction drain timeout, the value must not be negative")
errInvalidTenantShardSize = errors.New("invalid tenant shard size, the value must be greater than 0")
supportedCompactionStrategies = []string{util.CompactionStrategyDefault, util.CompactionStrategyPartitioning}
errInvalidCompactionStrategy = errors.New("invalid compaction strategy")
Expand Down Expand Up @@ -269,6 +270,7 @@ type Config struct {
CompactionInterval time.Duration `yaml:"compaction_interval"`
CompactionRetries int `yaml:"compaction_retries"`
CompactionConcurrency int `yaml:"compaction_concurrency"`
CompactionDrainTimeout time.Duration `yaml:"compaction_drain_timeout"`
CleanupInterval time.Duration `yaml:"cleanup_interval"`
CleanupConcurrency int `yaml:"cleanup_concurrency"`
DeletionDelay time.Duration `yaml:"deletion_delay"`
Expand Down Expand Up @@ -333,6 +335,7 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
f.DurationVar(&cfg.CompactionInterval, "compactor.compaction-interval", time.Hour, "The frequency at which the compaction runs")
f.IntVar(&cfg.CompactionRetries, "compactor.compaction-retries", 3, "How many times to retry a failed compaction within a single compaction run.")
f.IntVar(&cfg.CompactionConcurrency, "compactor.compaction-concurrency", 1, "Max number of concurrent compactions running.")
f.DurationVar(&cfg.CompactionDrainTimeout, "compactor.compaction-drain-timeout", 0, "How long to let a compaction that is already running finish once shutdown has been requested, before cancelling it. As soon as shutdown is requested the compactor stops planning new compaction groups and stops picking up further tenants, regardless of this setting. 0 cancels the running compaction immediately, discarding the work it has done so far. A compaction is only allowed to finish if the process is given at least this long to terminate, so this value should be below the deployment's termination grace period.")
f.DurationVar(&cfg.CleanupInterval, "compactor.cleanup-interval", 15*time.Minute, "How frequently compactor should run blocks cleanup and maintenance, as well as update the bucket index.")
f.IntVar(&cfg.CleanupConcurrency, "compactor.cleanup-concurrency", 20, "Max number of tenants for which blocks cleanup and maintenance should run concurrently.")
f.BoolVar(&cfg.ShardingEnabled, "compactor.sharding-enabled", false, "Shard tenants across multiple compactor instances. Sharding is required if you run multiple compactor instances, in order to coordinate compactions and avoid race conditions leading to the same tenant blocks simultaneously compacted by different instances.")
Expand Down Expand Up @@ -391,6 +394,10 @@ func (cfg *Config) Validate(limits validation.Limits) error {
return errInvalidBlockMergeFanIn
}

if cfg.CompactionDrainTimeout < 0 {
return errInvalidCompactionDrainTimeout
}

// Make sure a valid sharding strategy is being used
if !slices.Contains(supportedShardingStrategies, cfg.ShardingStrategy) {
return errInvalidShardingStrategy
Expand Down Expand Up @@ -459,6 +466,9 @@ type Compactor struct {
// Client used to run operations on the bucket storing blocks.
bucketClient objstore.InstrumentedBucket

compactionCtx context.Context
cancelCompaction context.CancelFunc

// Ring used for sharding compactions.
ringLifecycler *ring.Lifecycler
ring *ring.Ring
Expand Down Expand Up @@ -657,23 +667,30 @@ func newCompactor(
}

// Start the compactor.
func (c *Compactor) starting(ctx context.Context) error {
func (c *Compactor) starting(ctx context.Context) (err error) {
begin := time.Now()
defer func() {
c.CompactorStartDurationSeconds.Set(time.Since(begin).Seconds())
level.Info(c.logger).Log("msg", "compactor started", "duration", time.Since(begin), "duration_ms", time.Since(begin).Milliseconds())
}()

var err error
// The TSDB compactor, the GCS token source and the ring lifecycler keep the
// context they are started with, so all three use the compaction context.
c.compactionCtx, c.cancelCompaction = compactionContext(ctx, c.compactorCfg.CompactionDrainTimeout)
Comment thread
alexqyle marked this conversation as resolved.
Resolved
defer func() {
if err != nil {
c.cancelCompaction()
}
}()

// Create bucket client.
c.bucketClient, err = c.bucketClientFactory(ctx)
c.bucketClient, err = c.bucketClientFactory(c.compactionCtx)
if err != nil {
return errors.Wrap(err, "failed to create bucket client")
}

// Create blocks compactor dependencies.
c.blocksCompactor, c.blocksPlannerFactory, err = c.blocksCompactorFactory(ctx, c.compactorCfg, c.logger, c.registerer)
c.blocksCompactor, c.blocksPlannerFactory, err = c.blocksCompactorFactory(c.compactionCtx, c.compactorCfg, c.logger, c.registerer)
if err != nil {
return errors.Wrap(err, "failed to initialize compactor dependencies")
}
Expand Down Expand Up @@ -728,7 +745,7 @@ func (c *Compactor) starting(ctx context.Context) error {
c.ringSubservicesWatcher = services.NewFailureWatcher()
c.ringSubservicesWatcher.WatchManager(c.ringSubservices)

err = services.StartManagerAndAwaitHealthy(ctx, c.ringSubservices)
err = services.StartManagerAndAwaitHealthy(c.compactionCtx, c.ringSubservices)
}

if err != nil {
Expand Down Expand Up @@ -800,6 +817,7 @@ func (c *Compactor) stopping(_ error) error {
defer func() {
level.Info(c.logger).Log("msg", "compactor stopped", "duration", time.Since(begin), "duration_ms", time.Since(begin).Milliseconds())
}()
defer c.cancelCompaction()

ctx := context.Background()

Expand All @@ -810,6 +828,29 @@ func (c *Compactor) stopping(_ error) error {
return nil
}

// compactionContext detaches from ctx so an in-flight compaction can finish
// after shutdown, for up to drainTimeout. Zero returns ctx itself.
func compactionContext(ctx context.Context, drainTimeout time.Duration) (context.Context, context.CancelFunc) {
if drainTimeout <= 0 {
return ctx, func() {}
}

compactionCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
go func() {
select {
case <-ctx.Done():
select {
case <-time.After(drainTimeout):
case <-compactionCtx.Done():
}
case <-compactionCtx.Done():
}
cancel()
}()

return compactionCtx, cancel
}

func (c *Compactor) running(ctx context.Context) error {
// Ensure an initial cleanup occurred as first thing when running compactor.
if err := services.StartAndAwaitRunning(ctx, c.blocksCleaner); err != nil {
Expand All @@ -828,7 +869,7 @@ func (c *Compactor) running(ctx context.Context) error {
return ctx.Err()
case <-time.After(time.Duration(rand.Int63n(int64(float64(c.compactorCfg.CompactionInterval) * 0.1)))):
}
c.compactUsers(ctx)
c.compactUsers(ctx, c.compactionCtx)

ticker := time.NewTicker(c.compactorCfg.CompactionInterval)
defer ticker.Stop()
Expand All @@ -839,7 +880,7 @@ func (c *Compactor) running(ctx context.Context) error {
// Insert jitter right before compaction starts, so that there will always
// have jitter even compaction time is longer than CompactionInterval
time.Sleep(time.Duration(rand.Int63n(int64(float64(c.compactorCfg.CompactionInterval) * 0.1))))
c.compactUsers(ctx)
c.compactUsers(ctx, c.compactionCtx)
case <-ctx.Done():
return nil
case err := <-c.ringSubservicesWatcher.Chan():
Expand All @@ -848,7 +889,9 @@ func (c *Compactor) running(ctx context.Context) error {
}
}

func (c *Compactor) compactUsers(ctx context.Context) {
// ctx decides whether another tenant is picked up; compactionCtx runs the
// compaction and can outlive ctx by -compactor.compaction-drain-timeout.
func (c *Compactor) compactUsers(ctx, compactionCtx context.Context) {
succeeded := false
interrupted := false
compactionErrorCount := 0
Expand Down Expand Up @@ -934,9 +977,9 @@ func (c *Compactor) compactUsers(ctx context.Context) {

level.Info(c.logger).Log("msg", "starting compaction of user blocks", "user", userID)

if err = c.compactUserWithRetries(ctx, userID); err != nil {
if err = c.compactUserWithRetries(compactionCtx, ctx, userID); err != nil {
// TODO: patch thanos error types to support errors.Is(err, context.Canceled) here
if ctx.Err() != nil && ctx.Err() == context.Canceled {
if compactionCtx.Err() != nil && compactionCtx.Err() == context.Canceled {
interrupted = true
level.Info(c.logger).Log("msg", "interrupting compaction of user blocks", "user", userID)
return
Expand Down Expand Up @@ -981,7 +1024,7 @@ func (c *Compactor) compactUsers(ctx context.Context) {
succeeded = true
}

func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) error {
func (c *Compactor) compactUserWithRetries(ctx, shutdownCtx context.Context, userID string) error {
var lastErr error

retries := backoff.New(ctx, backoff.Config{
Expand All @@ -991,7 +1034,7 @@ func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) e
})

for retries.Ongoing() {
lastErr = c.compactUser(ctx, userID)
lastErr = c.compactUser(ctx, shutdownCtx, userID)
Comment thread
alexqyle marked this conversation as resolved.
Resolved
if lastErr == nil {
return nil
}
Expand All @@ -1010,6 +1053,12 @@ func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) e
}
c.compactorMetrics.compactionErrorsCount.WithLabelValues(userID, retriableError).Inc()

// Break rather than return, so lastErr is handled as when retries run
// out: a completed or visited partition is not counted as a failure.
if shutdownCtx.Err() != nil {
break
}

retries.Wait()
}

Expand All @@ -1021,7 +1070,35 @@ func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) e
return lastErr
}

func (c *Compactor) compactUser(ctx context.Context, userID string) error {
// shutdownGatedGrouper stops building new groups at shutdown. Under the
// partitioning strategy, building a group claims its partition in the bucket.
type shutdownGatedGrouper struct {
shutdownCtx context.Context
grouper compact.Grouper
}

func (g *shutdownGatedGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) ([]*compact.Group, error) {
if g.shutdownCtx.Err() != nil {
return nil, nil
}
return g.grouper.Groups(blocks)
}

// shutdownGatedPlanner stops planning groups already queued at shutdown. An
// empty plan is a group with nothing to do and does not ask for a rerun.
type shutdownGatedPlanner struct {
shutdownCtx context.Context
planner compact.Planner
}

func (p *shutdownGatedPlanner) Plan(ctx context.Context, metasByMinTime []*metadata.Meta, errChan chan error, extensions any) ([]*metadata.Meta, error) {
if p.shutdownCtx.Err() != nil {
return nil, nil
}
return p.planner.Plan(ctx, metasByMinTime, errChan, extensions)
}

func (c *Compactor) compactUser(ctx, shutdownCtx context.Context, userID string) error {
bucket := newParquetFilteredBucket(bucket.NewUserBucketClient(userID, c.bucketClient, c.limits))

reg := prometheus.NewRegistry()
Expand Down Expand Up @@ -1116,11 +1193,18 @@ func (c *Compactor) compactUser(ctx context.Context, userID string) error {

currentCtx, cancel := context.WithCancel(ctx)
defer cancel()

planner := c.blocksPlannerFactory(currentCtx, bucket, ulogger, c.compactorCfg, noCompactMarkerFilter, c.ringLifecycler, userID, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, c.compactorMetrics, ignoreDeletionMarkFilter)
grouper := c.blocksGrouperFactory(currentCtx, c.compactorCfg, bucket, ulogger, c.BlocksMarkedForNoCompaction, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, syncerMetrics, c.compactorMetrics, c.ring, c.ringLifecycler, c.limits, userID, noCompactMarkerFilter, c.ingestionReplicationFactor)
if c.compactorCfg.CompactionDrainTimeout > 0 {
planner = &shutdownGatedPlanner{shutdownCtx: shutdownCtx, planner: planner}
grouper = &shutdownGatedGrouper{shutdownCtx: shutdownCtx, grouper: grouper}
}
compactor, err := compact.NewBucketCompactorWithCheckerAndCallback(
ulogger,
syncer,
c.blocksGrouperFactory(currentCtx, c.compactorCfg, bucket, ulogger, c.BlocksMarkedForNoCompaction, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, syncerMetrics, c.compactorMetrics, c.ring, c.ringLifecycler, c.limits, userID, noCompactMarkerFilter, c.ingestionReplicationFactor),
c.blocksPlannerFactory(currentCtx, bucket, ulogger, c.compactorCfg, noCompactMarkerFilter, c.ringLifecycler, userID, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, c.compactorMetrics, ignoreDeletionMarkFilter),
grouper,
planner,
c.blocksCompactor,
c.blockDeletableCheckerFactory(currentCtx, bucket, ulogger),
c.compactionLifecycleCallbackFactory(currentCtx, bucket, ulogger, c.compactorCfg.MetaSyncConcurrency, c.compactorCfg.BlockMergeFanIn, c.compactDirForUser(userID), userID, c.compactorMetrics),
Expand Down
6 changes: 3 additions & 3 deletions pkg/compactor/compactor_paritioning_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1630,7 +1630,7 @@ func TestPartitionCompactor_DeleteLocalSyncFiles(t *testing.T) {

// Run a compaction cycle on the first compactor: it is alone in the ring, so
// it owns (and syncs) all the users.
c1.compactUsers(context.Background())
c1.compactUsers(context.Background(), context.Background())
require.Equal(t, numUsers, len(c1.listTenantsWithMetaSyncDirectories()))

require.NoError(t, os.Mkdir(c1.metaSyncDirForUser("new-user"), 0600))
Expand Down Expand Up @@ -1660,14 +1660,14 @@ func TestPartitionCompactor_DeleteLocalSyncFiles(t *testing.T) {

// Run a compaction cycle on the second compactor: with pinned tokens it owns
// exactly half of the users and creates a meta-sync directory for each of them.
c2.compactUsers(context.Background())
c2.compactUsers(context.Background(), context.Background())

// Let's check how many users second compactor has.
c2Users := len(c2.listTenantsWithMetaSyncDirectories())
require.Equal(t, numUsers/2, c2Users)

// Force new compaction cycle on first compactor. It will run the cleanup of un-owned users at the end of compaction cycle.
c1.compactUsers(context.Background())
c1.compactUsers(context.Background(), context.Background())
c1Users := len(c1.listTenantsWithMetaSyncDirectories())

// Now compactor 1 should have cleaned the sync files of the users it no longer
Expand Down
Loading