Skip to content

Commit 46fc74b

Browse files
committed
store: lock around iterating over s.blocks
Hold a lock around s.blocks when iterating over it. I have experienced a case where a block had been added to a blockSet twice somehow and it being somehow removed from s.blocks is the only way it could happen. This is the only "bad" thing I've been able to spot. Remove the removeBlock() function as IMHO it is too shallow. Better to hold the lock consistently. Signed-off-by: Giedrius Statkevičius <[email protected]>
1 parent 57efc2a commit 46fc74b

File tree

7 files changed

+79
-51
lines changed

7 files changed

+79
-51
lines changed

docs/getting-started.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ See up to date [jsonnet mixins](https://github.com/thanos-io/thanos/tree/main/mi
162162
* [HelloFresh blog posts part 1](https://engineering.hellofresh.com/monitoring-at-hellofresh-part-1-architecture-677b4bd6b728)
163163
* [HelloFresh blog posts part 2](https://engineering.hellofresh.com/monitoring-at-hellofresh-part-2-operating-the-monitoring-system-8175cd939c1d)
164164
* [Thanos deployment](https://www.metricfire.com/blog/ha-kubernetes-monitoring-using-prometheus-and-thanos)
165-
* [Taboola user story](https://blog.taboola.com/monitoring-and-metering-scale/)
165+
* [Taboola user story](https://www.taboola.com/engineering/monitoring-and-metering-scale/)
166166
* [Thanos via Prometheus Operator](https://kkc.github.io/2019/02/10/prometheus-operator-with-thanos/)
167167

168168
* 2018:

pkg/extprom/http/instrument_client.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ type ClientMetrics struct {
2323

2424
// NewClientMetrics creates a new instance of ClientMetrics.
2525
// It will also register the metrics with the included register.
26-
// This ClientMetrics should be re-used for diff clients with the same purpose.
26+
// This ClientMetrics should be reused for diff clients with the same purpose.
2727
// e.g. 1 ClientMetrics should be used for all the clients that talk to Alertmanager.
2828
func NewClientMetrics(reg prometheus.Registerer) *ClientMetrics {
2929
var m ClientMetrics

pkg/query/endpointset.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ func (e *EndpointSet) Update(ctx context.Context) {
366366
if er.HasStoreAPI() && (er.ComponentType() == component.Sidecar || er.ComponentType() == component.Rule) &&
367367
stats[component.Sidecar.String()][extLset]+stats[component.Rule.String()][extLset] > 0 {
368368

369-
level.Warn(e.logger).Log("msg", "found duplicate storeEndpoints producer (sidecar or ruler). This is not advices as it will malform data in in the same bucket",
369+
level.Warn(e.logger).Log("msg", "found duplicate storeEndpoints producer (sidecar or ruler). This is not advised as it will malform data in in the same bucket",
370370
"address", addr, "extLset", extLset, "duplicates", fmt.Sprintf("%v", stats[component.Sidecar.String()][extLset]+stats[component.Rule.String()][extLset]+1))
371371
}
372372
stats[er.ComponentType().String()][extLset]++

pkg/runutil/runutil.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
// The rununtil.Exhaust* family of functions provide the same functionality but
4646
// they take an io.ReadCloser and they exhaust the whole reader before closing
4747
// them. They are useful when trying to use http keep-alive connections because
48-
// for the same connection to be re-used the whole response body needs to be
48+
// for the same connection to be reused the whole response body needs to be
4949
// exhausted.
5050
package runutil
5151

pkg/store/bucket.go

Lines changed: 45 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,7 @@ func (s *BucketStore) SyncBlocks(ctx context.Context) error {
742742
continue
743743
}
744744
if err := s.addBlock(ctx, meta); err != nil {
745+
level.Warn(s.logger).Log("msg", "adding block failed", "err", err, "id", meta.ULID.String())
745746
continue
746747
}
747748
}
@@ -766,17 +767,37 @@ func (s *BucketStore) SyncBlocks(ctx context.Context) error {
766767
return metaFetchErr
767768
}
768769

770+
var cleanupBlocks []*bucketBlock
771+
s.mtx.RLock()
772+
keys := make([]ulid.ULID, 0, len(s.blocks))
773+
for k := range s.blocks {
774+
keys = append(keys, k)
775+
}
776+
s.mtx.RUnlock()
777+
769778
// Drop all blocks that are no longer present in the bucket.
770-
for id := range s.blocks {
779+
for _, id := range keys {
771780
if _, ok := metas[id]; ok {
772781
continue
773782
}
774-
if err := s.removeBlock(id); err != nil {
775-
level.Warn(s.logger).Log("msg", "drop of outdated block failed", "block", id, "err", err)
776-
s.metrics.blockDropFailures.Inc()
783+
784+
s.mtx.Lock()
785+
b := s.blocks[id]
786+
if b == nil {
787+
// NOTE(GiedriusS): this cannot really happen because SyncBlocks() is called in one thread only but just in case.
788+
s.mtx.Unlock()
789+
continue
777790
}
778-
level.Info(s.logger).Log("msg", "dropped outdated block", "block", id)
791+
lset := labels.FromMap(b.meta.Thanos.Labels)
792+
s.blockSets[lset.Hash()].remove(id)
793+
delete(s.blocks, id)
794+
s.mtx.Unlock()
795+
796+
s.metrics.blocksLoaded.Dec()
779797
s.metrics.blockDrops.Inc()
798+
cleanupBlocks = append(cleanupBlocks, b)
799+
800+
level.Info(s.logger).Log("msg", "dropped outdated block", "block", id)
780801
}
781802

782803
// Sync advertise labels.
@@ -789,6 +810,25 @@ func (s *BucketStore) SyncBlocks(ctx context.Context) error {
789810
return strings.Compare(s.advLabelSets[i].String(), s.advLabelSets[j].String()) < 0
790811
})
791812
s.mtx.Unlock()
813+
814+
go func() {
815+
for _, b := range cleanupBlocks {
816+
var errs prometheus.MultiError
817+
818+
errs.Append(b.Close())
819+
820+
if b.dir != "" {
821+
errs.Append(os.RemoveAll(b.dir))
822+
}
823+
824+
if len(errs) == 0 {
825+
return
826+
}
827+
828+
level.Warn(s.logger).Log("msg", "close of outdated block failed", "block", b.meta.ULID.String(), "err", errs.Error())
829+
s.metrics.blockDropFailures.Inc()
830+
}
831+
}()
792832
return nil
793833
}
794834

@@ -921,32 +961,6 @@ func (s *BucketStore) addBlock(ctx context.Context, meta *metadata.Meta) (err er
921961
return nil
922962
}
923963

924-
func (s *BucketStore) removeBlock(id ulid.ULID) error {
925-
s.mtx.Lock()
926-
b, ok := s.blocks[id]
927-
if ok {
928-
lset := labels.FromMap(b.meta.Thanos.Labels)
929-
s.blockSets[lset.Hash()].remove(id)
930-
delete(s.blocks, id)
931-
}
932-
s.mtx.Unlock()
933-
934-
if !ok {
935-
return nil
936-
}
937-
938-
s.metrics.blocksLoaded.Dec()
939-
if err := b.Close(); err != nil {
940-
return errors.Wrap(err, "close block")
941-
}
942-
943-
if b.dir == "" {
944-
return nil
945-
}
946-
947-
return os.RemoveAll(b.dir)
948-
}
949-
950964
// TimeRange returns the minimum and maximum timestamp of data available in the store.
951965
func (s *BucketStore) TimeRange() (mint, maxt int64) {
952966
s.mtx.RLock()

pkg/store/bucket_test.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1827,7 +1827,10 @@ func TestBucketSeries_OneBlock_InMemIndexCacheSegfault(t *testing.T) {
18271827
testutil.Equals(t, numSeries, len(srv.SeriesSet))
18281828
})
18291829
t.Run("remove second block. Cache stays. Ask for first again.", func(t *testing.T) {
1830-
testutil.Ok(t, store.removeBlock(b2.meta.ULID))
1830+
b := store.blocks[b2.meta.ULID]
1831+
lset := labels.FromMap(b.meta.Thanos.Labels)
1832+
store.blockSets[lset.Hash()].remove(b2.meta.ULID)
1833+
delete(store.blocks, b2.meta.ULID)
18311834

18321835
srv := newStoreSeriesServer(context.Background())
18331836
testutil.Ok(t, store.Series(&storepb.SeriesRequest{

test/e2e/store_gateway_test.go

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"time"
2020

2121
"github.com/cortexproject/promqlsmith"
22+
"github.com/efficientgo/core/backoff"
2223
"github.com/efficientgo/core/testutil"
2324
"github.com/efficientgo/e2e"
2425
e2edb "github.com/efficientgo/e2e/db"
@@ -816,7 +817,13 @@ metafile_content_ttl: 0s`
816817
// thanos_blocks_meta_synced: 1x loadedMeta 0x labelExcludedMeta 0x TooFreshMeta.
817818
for _, st := range []*e2eobs.Observable{store1, store2, store3} {
818819
t.Run(st.Name(), func(t *testing.T) {
819-
testutil.Ok(t, st.WaitSumMetrics(e2emon.Equals(1), "thanos_blocks_meta_synced"))
820+
testutil.Ok(t, st.WaitSumMetricsWithOptions(e2emon.Equals(1), []string{"thanos_blocks_meta_synced"}, e2emon.WaitMissingMetrics(), e2emon.WithWaitBackoff(
821+
&backoff.Config{
822+
Min: 1 * time.Second,
823+
Max: 10 * time.Second,
824+
MaxRetries: 30,
825+
},
826+
)))
820827
testutil.Ok(t, st.WaitSumMetrics(e2emon.Equals(0), "thanos_blocks_meta_sync_failures_total"))
821828

822829
testutil.Ok(t, st.WaitSumMetrics(e2emon.Equals(1), "thanos_bucket_store_blocks_loaded"))
@@ -826,23 +833,27 @@ metafile_content_ttl: 0s`
826833
}
827834

828835
t.Run("query with groupcache loading from object storage", func(t *testing.T) {
829-
queryAndAssertSeries(t, ctx, q.Endpoint("http"), func() string { return testQuery },
830-
time.Now, promclient.QueryOptions{
831-
Deduplicate: false,
832-
},
833-
[]model.Metric{
834-
{
835-
"a": "1",
836-
"b": "2",
837-
"ext1": "value1",
838-
"replica": "1",
836+
for i := 0; i < 3; i++ {
837+
queryAndAssertSeries(t, ctx, q.Endpoint("http"), func() string { return testQuery },
838+
time.Now, promclient.QueryOptions{
839+
Deduplicate: false,
839840
},
840-
},
841-
)
841+
[]model.Metric{
842+
{
843+
"a": "1",
844+
"b": "2",
845+
"ext1": "value1",
846+
"replica": "1",
847+
},
848+
},
849+
)
850+
}
842851

843852
for _, st := range []*e2eobs.Observable{store1, store2, store3} {
844-
testutil.Ok(t, st.WaitSumMetricsWithOptions(e2emon.Greater(0), []string{`thanos_cache_groupcache_loads_total`}))
845-
testutil.Ok(t, st.WaitSumMetricsWithOptions(e2emon.Greater(0), []string{`thanos_store_bucket_cache_operation_hits_total`}, e2emon.WithLabelMatchers(matchers.MustNewMatcher(matchers.MatchEqual, "config", "chunks"))))
853+
t.Run(st.Name(), func(t *testing.T) {
854+
testutil.Ok(t, st.WaitSumMetricsWithOptions(e2emon.Greater(0), []string{`thanos_cache_groupcache_loads_total`}))
855+
testutil.Ok(t, st.WaitSumMetricsWithOptions(e2emon.Greater(0), []string{`thanos_store_bucket_cache_operation_hits_total`}, e2emon.WithLabelMatchers(matchers.MustNewMatcher(matchers.MatchEqual, "config", "chunks"))))
856+
})
846857
}
847858
})
848859

0 commit comments

Comments
 (0)