diff --git a/CHANGELOG.md b/CHANGELOG.md index f32e39e4ef..d290fdbf3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `-.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 diff --git a/docs/blocks-storage/compactor.md b/docs/blocks-storage/compactor.md index 23c03136fb..daf67b251f 100644 --- a/docs/blocks-storage/compactor.md +++ b/docs/blocks-storage/compactor.md @@ -144,6 +144,17 @@ compactor: # CLI flag: -compactor.compaction-concurrency [compaction_concurrency: | 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: | default = 0s] + # How frequently compactor should run blocks cleanup and maintenance, as well # as update the bucket index. # CLI flag: -compactor.cleanup-interval diff --git a/docs/configuration/config-file-reference.md b/docs/configuration/config-file-reference.md index 9fd5b281df..2f2df333c2 100644 --- a/docs/configuration/config-file-reference.md +++ b/docs/configuration/config-file-reference.md @@ -3146,6 +3146,16 @@ The `compactor_config` configures the compactor for the blocks storage. # CLI flag: -compactor.compaction-concurrency [compaction_concurrency: | 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: | default = 0s] + # How frequently compactor should run blocks cleanup and maintenance, as well as # update the bucket index. # CLI flag: -compactor.cleanup-interval diff --git a/pkg/compactor/compactor.go b/pkg/compactor/compactor.go index 33f7c1ebce..60b64ed738 100644 --- a/pkg/compactor/compactor.go +++ b/pkg/compactor/compactor.go @@ -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") @@ -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"` @@ -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.") @@ -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 @@ -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 @@ -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) + 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") } @@ -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 { @@ -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() @@ -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 { @@ -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() @@ -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(): @@ -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 @@ -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 @@ -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{ @@ -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) if lastErr == nil { return nil } @@ -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() } @@ -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() @@ -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), diff --git a/pkg/compactor/compactor_paritioning_test.go b/pkg/compactor/compactor_paritioning_test.go index 1dff481f06..470051b8bc 100644 --- a/pkg/compactor/compactor_paritioning_test.go +++ b/pkg/compactor/compactor_paritioning_test.go @@ -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)) @@ -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 diff --git a/pkg/compactor/compactor_test.go b/pkg/compactor/compactor_test.go index abb9268ea1..6ddcdb8274 100644 --- a/pkg/compactor/compactor_test.go +++ b/pkg/compactor/compactor_test.go @@ -34,6 +34,7 @@ import ( "github.com/thanos-io/thanos/pkg/block" "github.com/thanos-io/thanos/pkg/block/metadata" "github.com/thanos-io/thanos/pkg/compact" + "go.uber.org/atomic" "gopkg.in/yaml.v2" "github.com/cortexproject/cortex/pkg/ring" @@ -1628,6 +1629,11 @@ func prepareConfig() Config { } func prepare(t *testing.T, compactorCfg Config, bucketClient objstore.InstrumentedBucket, limits *validation.Limits) (*Compactor, *tsdbCompactorMock, *tsdbPlannerMock, *concurrency.SyncBuffer, prometheus.Gatherer) { + return prepareWithGrouperFactory(t, compactorCfg, bucketClient, limits, nil) +} + +// A nil grouperFactory keeps the factory the sharding strategy selects. +func prepareWithGrouperFactory(t *testing.T, compactorCfg Config, bucketClient objstore.InstrumentedBucket, limits *validation.Limits, grouperFactory BlocksGrouperFactory) (*Compactor, *tsdbCompactorMock, *tsdbPlannerMock, *concurrency.SyncBuffer, prometheus.Gatherer) { storageCfg := cortex_tsdb.BlocksStorageConfig{} flagext.DefaultValues(&storageCfg) storageCfg.BucketStore.BlockDiscoveryStrategy = string(cortex_tsdb.RecursiveDiscovery) @@ -1657,6 +1663,7 @@ func prepare(t *testing.T, compactorCfg Config, bucketClient objstore.Instrument } blocksCompactorFactory := func(ctx context.Context, cfg Config, logger log.Logger, reg prometheus.Registerer) (compact.Compactor, PlannerFactory, error) { + tsdbCompactor.ctx = ctx return tsdbCompactor, func(ctx context.Context, bkt objstore.InstrumentedBucket, _ log.Logger, _ Config, noCompactMarkFilter *compact.GatherNoCompactionMarkFilter, ringLifecycle *ring.Lifecycler, _ string, _ prometheus.Counter, _ prometheus.Counter, _ *compactorMetrics, _ *block.IgnoreDeletionMarkFilter) compact.Planner { tsdbPlanner.noCompactMarkFilters = append(tsdbPlanner.noCompactMarkFilters, noCompactMarkFilter) @@ -1666,9 +1673,12 @@ func prepare(t *testing.T, compactorCfg Config, bucketClient objstore.Instrument } var blocksGrouperFactory BlocksGrouperFactory - if compactorCfg.ShardingStrategy == util.ShardingStrategyShuffle { + switch { + case grouperFactory != nil: + blocksGrouperFactory = grouperFactory + case compactorCfg.ShardingStrategy == util.ShardingStrategyShuffle: blocksGrouperFactory = ShuffleShardingGrouperFactory - } else { + default: blocksGrouperFactory = DefaultBlocksGrouperFactory } @@ -1680,6 +1690,9 @@ func prepare(t *testing.T, compactorCfg Config, bucketClient objstore.Instrument type tsdbCompactorMock struct { mock.Mock + + // A real TSDB compactor checks the context it was built with while merging. + ctx context.Context } func (m *tsdbCompactorMock) Plan(dir string) ([]string, error) { @@ -1930,7 +1943,7 @@ func TestCompactor_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)) @@ -1960,14 +1973,14 @@ func TestCompactor_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 @@ -2071,6 +2084,446 @@ func TestCompactor_ShouldNotTreatInterruptionsAsErrors(t *testing.T) { require.NotContains(t, logs.String(), `level=error`) } +func TestCompactor_ShouldLetRunningCompactionFinishOnShutdownWhenDrainTimeoutIsSet(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + + c, _, tsdbPlanner, _, registry := prepare(t, cfg, bucketClient, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var planCtxErr error + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{}, nil).Run(func(args mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + planCtxErr = args.Get(0).(context.Context).Err() + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + // Cancelling the start context cancels the service context synchronously. + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.NoError(t, planCtxErr) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + + # TYPE cortex_compactor_runs_interrupted_total counter + # HELP cortex_compactor_runs_interrupted_total Total number of compaction runs interrupted. + cortex_compactor_runs_interrupted_total 0 + + # TYPE cortex_compactor_runs_failed_total counter + # HELP cortex_compactor_runs_failed_total Total number of compaction runs failed. + cortex_compactor_runs_failed_total 0 + `), + "cortex_compactor_runs_completed_total", + "cortex_compactor_runs_interrupted_total", + "cortex_compactor_runs_failed_total", + )) +} + +func TestCompactor_ShouldCancelRunningCompactionWhenDrainTimeoutExpires(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = 100 * time.Millisecond + + c, _, tsdbPlanner, _, _ := prepare(t, cfg, bucketClient, nil) + + planCalled := make(chan struct{}) + planCtxErr := make(chan error, 1) + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{}, nil).Run(func(args mock.Arguments) { + once.Do(func() { + planCtx := args.Get(0).(context.Context) + close(planCalled) + select { + case <-planCtx.Done(): + case <-time.After(10 * time.Second): + } + planCtxErr <- planCtx.Err() + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + + assert.Equal(t, context.Canceled, <-planCtxErr) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) +} + +// Stands in for the sharding groupers, which produce several groups per pass. +type duplicatingGrouper struct { + grouper compact.Grouper +} + +func (g *duplicatingGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) ([]*compact.Group, error) { + groups, err := g.grouper.Groups(blocks) + if err != nil { + return nil, err + } + + out := make([]*compact.Group, 0, len(groups)*2) + out = append(out, groups...) + out = append(out, groups...) + return out, nil +} + +func TestCompactor_ShouldStopPlanningNewGroupsOnceShutdownIsRequested(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = 3 * time.Second + + c, tsdbCompactor, tsdbPlanner, _, registry := prepareWithGrouperFactory(t, cfg, bucketClient, nil, func(ctx context.Context, cfg Config, bkt objstore.InstrumentedBucket, logger log.Logger, blocksMarkedForNoCompact prometheus.Counter, blockVisitMarkerReadFailed prometheus.Counter, blockVisitMarkerWriteFailed prometheus.Counter, syncerMetrics *compact.SyncerMetrics, compactorMetrics *compactorMetrics, r *ring.Ring, ringLifecycler *ring.Lifecycler, limit Limits, userID string, noCompactionMarkFilter *compact.GatherNoCompactionMarkFilter, ingestionReplicationFactor int) compact.Grouper { + return &duplicatingGrouper{ + grouper: DefaultBlocksGrouperFactory(ctx, cfg, bkt, logger, blocksMarkedForNoCompact, blockVisitMarkerReadFailed, blockVisitMarkerWriteFailed, syncerMetrics, compactorMetrics, r, ringLifecycler, limit, userID, noCompactionMarkFilter, ingestionReplicationFactor), + } + }) + + // An empty compaction result makes thanos ask for another pass. + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + // Non-zero samples stop thanos marking the sources for deletion. + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + tsdbPlanner.AssertNumberOfCalls(t, "Plan", 1) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + + # TYPE cortex_compactor_runs_interrupted_total counter + # HELP cortex_compactor_runs_interrupted_total Total number of compaction runs interrupted. + cortex_compactor_runs_interrupted_total 0 + `), + "cortex_compactor_runs_completed_total", + "cortex_compactor_runs_interrupted_total", + )) +} + +func TestCompactor_ShouldNotCancelTheMergeOnShutdownWhenDrainTimeoutIsSet(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + + c, tsdbCompactor, tsdbPlanner, _, registry := prepare(t, cfg, bucketClient, nil) + + mergeCalled := make(chan struct{}) + releaseMerge := make(chan struct{}) + var mergeCtxErr error + var once sync.Once + + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(mergeCalled) + <-releaseMerge + mergeCtxErr = tsdbCompactor.ctx.Err() + }) + }) + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-mergeCalled + cancel() + close(releaseMerge) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.NoError(t, mergeCtxErr) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + `), + "cortex_compactor_runs_completed_total", + )) +} + +func TestCompactor_ShouldStayInTheRingWhileDraining(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + ringStore, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil) + t.Cleanup(func() { assert.NoError(t, closer.Close()) }) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + cfg.ShardingEnabled = true + cfg.ShardingRing.InstanceID = "compactor-1" + cfg.ShardingRing.InstanceAddr = "1.2.3.4" + cfg.ShardingRing.KVStore.Mock = ringStore + + c, tsdbCompactor, tsdbPlanner, _, _ := prepare(t, cfg, bucketClient, nil) + + mergeCalled := make(chan struct{}) + releaseMerge := make(chan struct{}) + var once sync.Once + + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(mergeCalled) + <-releaseMerge + }) + }) + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil) + + isActive := func() bool { + d, err := ringStore.Get(context.Background(), ringKey) + require.NoError(t, err) + desc, ok := d.(*ring.Desc) + if !ok { + return false + } + instance, ok := desc.Ingesters[cfg.ShardingRing.InstanceID] + return ok && instance.State == ring.ACTIVE + } + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-mergeCalled + cancel() + + assert.Never(t, func() bool { return !isActive() }, 2*time.Second, 50*time.Millisecond) + + close(releaseMerge) + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.False(t, isActive()) +} + +func TestCompactor_ShouldNotRetryAFailedCompactionAfterShutdown(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + + c, _, tsdbPlanner, _, registry := prepare(t, cfg, bucketClient, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var once sync.Once + + // A planning error is retriable, unlike a merge error, which thanos halts on. + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{}, errors.New("plan failed")).Run(func(mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 0 + + # TYPE cortex_compactor_runs_failed_total counter + # HELP cortex_compactor_runs_failed_total Total number of compaction runs failed. + cortex_compactor_runs_failed_total 1 + `), + "cortex_compactor_runs_completed_total", + "cortex_compactor_runs_failed_total", + )) +} + +type countingGrouper struct { + calls *atomic.Int64 + grouper compact.Grouper +} + +func (g *countingGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) ([]*compact.Group, error) { + g.calls.Add(1) + return g.grouper.Groups(blocks) +} + +func TestCompactor_ShouldStopBuildingGroupsOnceShutdownIsRequested(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = 3 * time.Second + + var groupsCalls atomic.Int64 + grouperFactory := func(ctx context.Context, cfg Config, bkt objstore.InstrumentedBucket, logger log.Logger, blocksMarkedForNoCompact prometheus.Counter, blockVisitMarkerReadFailed prometheus.Counter, blockVisitMarkerWriteFailed prometheus.Counter, syncerMetrics *compact.SyncerMetrics, compactorMetrics *compactorMetrics, r *ring.Ring, ringLifecycler *ring.Lifecycler, limit Limits, userID string, noCompactionMarkFilter *compact.GatherNoCompactionMarkFilter, ingestionReplicationFactor int) compact.Grouper { + return &countingGrouper{ + calls: &groupsCalls, + grouper: DefaultBlocksGrouperFactory(ctx, cfg, bkt, logger, blocksMarkedForNoCompact, blockVisitMarkerReadFailed, blockVisitMarkerWriteFailed, syncerMetrics, compactorMetrics, r, ringLifecycler, limit, userID, noCompactionMarkFilter, ingestionReplicationFactor), + } + } + + c, tsdbCompactor, tsdbPlanner, _, registry := prepareWithGrouperFactory(t, cfg, bucketClient, nil, grouperFactory) + + // An empty compaction result makes thanos run another pass over the tenant. + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.Equal(t, int64(1), groupsCalls.Load()) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + `), + "cortex_compactor_runs_completed_total", + )) +} + func TestCompactor_ShouldNotFailCompactionIfAccessDeniedErrDuringMetaSync(t *testing.T) { t.Parallel() diff --git a/schemas/cortex-config-schema.json b/schemas/cortex-config-schema.json index 4a45fe5668..35b1375e7e 100644 --- a/schemas/cortex-config-schema.json +++ b/schemas/cortex-config-schema.json @@ -3820,6 +3820,13 @@ "type": "number", "x-cli-flag": "compactor.compaction-concurrency" }, + "compaction_drain_timeout": { + "default": "0s", + "description": "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.", + "type": "string", + "x-cli-flag": "compactor.compaction-drain-timeout", + "x-format": "duration" + }, "compaction_interval": { "default": "1h0m0s", "description": "The frequency at which the compaction runs",