Skip to content

Commit e92e242

Browse files
committed
Creating a worker pool to be used on distributors
Signed-off-by: alanprot <[email protected]>
1 parent c9e3d5e commit e92e242

File tree

7 files changed

+126
-13
lines changed

7 files changed

+126
-13
lines changed

docs/configuration/config-file-reference.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2692,6 +2692,13 @@ ring:
26922692
# CLI flag: -distributor.ring.instance-interface-names
26932693
[instance_interface_names: <list of string> | default = [eth0 en0]]
26942694
2695+
# Number of go routines to handle push calls from distributors to ingesters.
2696+
# When no workers are available, a new goroutine will be spawned automatically.
2697+
# If set to 0 (default), workers are disabled, and a new goroutine will be
2698+
# created for each push request.
2699+
# CLI flag: -distributor.num-push-workers
2700+
[num_push_workers: <int> | default = 0]
2701+
26952702
instance_limits:
26962703
# Max ingestion rate (samples/sec) that this distributor will accept. This
26972704
# limit is per-distributor, not per-tenant. Additional push requests will be

pkg/alertmanager/distributor.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ func (d *Distributor) doQuorum(userID string, w http.ResponseWriter, r *http.Req
161161
var responses []*httpgrpc.HTTPResponse
162162
var responsesMtx sync.Mutex
163163
grpcHeaders := httpToHttpgrpcHeaders(r.Header)
164-
err = ring.DoBatch(r.Context(), RingOp, d.alertmanagerRing, []uint32{shardByUser(userID)}, func(am ring.InstanceDesc, _ []int) error {
164+
err = ring.DoBatch(r.Context(), RingOp, d.alertmanagerRing, nil, []uint32{shardByUser(userID)}, func(am ring.InstanceDesc, _ []int) error {
165165
// Use a background context to make sure all alertmanagers get the request even if we return early.
166166
localCtx := opentracing.ContextWithSpan(user.InjectOrgID(context.Background(), userID), opentracing.SpanFromContext(r.Context()))
167167
sp, localCtx := opentracing.StartSpanFromContext(localCtx, "Distributor.doQuorum")

pkg/alertmanager/multitenant.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,7 @@ func (am *MultitenantAlertmanager) ReplicateStateForUser(ctx context.Context, us
10991099
level.Debug(am.logger).Log("msg", "message received for replication", "user", userID, "key", part.Key)
11001100

11011101
selfAddress := am.ringLifecycler.GetInstanceAddr()
1102-
err := ring.DoBatch(ctx, RingOp, am.ring, []uint32{shardByUser(userID)}, func(desc ring.InstanceDesc, _ []int) error {
1102+
err := ring.DoBatch(ctx, RingOp, am.ring, nil, []uint32{shardByUser(userID)}, func(desc ring.InstanceDesc, _ []int) error {
11031103
if desc.GetAddr() == selfAddress {
11041104
return nil
11051105
}

pkg/distributor/distributor.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ type Distributor struct {
123123
latestSeenSampleTimestampPerUser *prometheus.GaugeVec
124124

125125
validateMetrics *validation.ValidateMetrics
126+
127+
asyncExecutor util.AsyncExecutor
126128
}
127129

128130
// Config contains the configuration required to
@@ -160,6 +162,11 @@ type Config struct {
160162
// from quorum number of zones will be included to reduce data merged and improve performance.
161163
ZoneResultsQuorumMetadata bool `yaml:"zone_results_quorum_metadata" doc:"hidden"`
162164

165+
// Number of go routines to handle push calls from distributors to ingesters.
166+
// If set to 0 (default), workers are disabled, and a new goroutine will be created for each push request.
167+
// When no workers are available, a new goroutine will be spawned automatically.
168+
NumPushWorkers int `yaml:"num_push_workers"`
169+
163170
// Limits for distributor
164171
InstanceLimits InstanceLimits `yaml:"instance_limits"`
165172

@@ -193,6 +200,7 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
193200
f.StringVar(&cfg.ShardingStrategy, "distributor.sharding-strategy", util.ShardingStrategyDefault, fmt.Sprintf("The sharding strategy to use. Supported values are: %s.", strings.Join(supportedShardingStrategies, ", ")))
194201
f.BoolVar(&cfg.ExtendWrites, "distributor.extend-writes", true, "Try writing to an additional ingester in the presence of an ingester not in the ACTIVE state. It is useful to disable this along with -ingester.unregister-on-shutdown=false in order to not spread samples to extra ingesters during rolling restarts with consistent naming.")
195202
f.BoolVar(&cfg.ZoneResultsQuorumMetadata, "distributor.zone-results-quorum-metadata", false, "Experimental, this flag may change in the future. If zone awareness and this both enabled, when querying metadata APIs (labels names and values for now), only results from quorum number of zones will be included.")
203+
f.IntVar(&cfg.NumPushWorkers, "distributor.num-push-workers", 0, "Number of go routines to handle push calls from distributors to ingesters. When no workers are available, a new goroutine will be spawned automatically. If set to 0 (default), workers are disabled, and a new goroutine will be created for each push request.")
196204

197205
f.Float64Var(&cfg.InstanceLimits.MaxIngestionRate, "distributor.instance-limits.max-ingestion-rate", 0, "Max ingestion rate (samples/sec) that this distributor will accept. This limit is per-distributor, not per-tenant. Additional push requests will be rejected. Current ingestion rate is computed as exponentially weighted moving average, updated every second. 0 = unlimited.")
198206
f.IntVar(&cfg.InstanceLimits.MaxInflightPushRequests, "distributor.instance-limits.max-inflight-push-requests", 0, "Max inflight push requests that this distributor can handle. This limit is per-distributor, not per-tenant. Additional requests will be rejected. 0 = unlimited.")
@@ -368,6 +376,10 @@ func New(cfg Config, clientConfig ingester_client.Config, limits *validation.Ove
368376
validateMetrics: validation.NewValidateMetrics(reg),
369377
}
370378

379+
if cfg.NumPushWorkers > 0 {
380+
d.asyncExecutor = util.NewWorkerPool(cfg.NumPushWorkers)
381+
}
382+
371383
promauto.With(reg).NewGauge(prometheus.GaugeOpts{
372384
Name: instanceLimitsMetric,
373385
Help: instanceLimitsMetricHelp,
@@ -823,7 +835,7 @@ func (d *Distributor) doBatch(ctx context.Context, req *cortexpb.WriteRequest, s
823835
op = ring.Write
824836
}
825837

826-
return ring.DoBatch(ctx, op, subRing, keys, func(ingester ring.InstanceDesc, indexes []int) error {
838+
return ring.DoBatch(ctx, op, subRing, d.asyncExecutor, keys, func(ingester ring.InstanceDesc, indexes []int) error {
827839
timeseries := make([]cortexpb.PreallocTimeseries, 0, len(indexes))
828840
var metadata []*cortexpb.MetricMetadata
829841

pkg/ring/batch.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@ import (
88
"go.uber.org/atomic"
99
"google.golang.org/grpc/status"
1010

11+
"github.com/cortexproject/cortex/pkg/util"
1112
"github.com/cortexproject/cortex/pkg/util/httpgrpcutil"
1213
)
1314

15+
var (
16+
noOpExecutor = util.NewNoOpExecutor()
17+
)
18+
1419
type batchTracker struct {
1520
rpcsPending atomic.Int32
1621
rpcsFailed atomic.Int32
@@ -66,12 +71,16 @@ func (i *itemTracker) getError() error {
6671
// cleanup() is always called, either on an error before starting the batches or after they all finish.
6772
//
6873
// Not implemented as a method on Ring so we can test separately.
69-
func DoBatch(ctx context.Context, op Operation, r ReadRing, keys []uint32, callback func(InstanceDesc, []int) error, cleanup func()) error {
74+
func DoBatch(ctx context.Context, op Operation, r ReadRing, e util.AsyncExecutor, keys []uint32, callback func(InstanceDesc, []int) error, cleanup func()) error {
7075
if r.InstancesCount() <= 0 {
7176
cleanup()
7277
return fmt.Errorf("DoBatch: InstancesCount <= 0")
7378
}
7479

80+
if e == nil {
81+
e = noOpExecutor
82+
}
83+
7584
expectedTrackers := len(keys) * (r.ReplicationFactor() + 1) / r.InstancesCount()
7685
itemTrackers := make([]itemTracker, len(keys))
7786
instances := make(map[string]instance, r.InstancesCount())
@@ -115,11 +124,11 @@ func DoBatch(ctx context.Context, op Operation, r ReadRing, keys []uint32, callb
115124

116125
wg.Add(len(instances))
117126
for _, i := range instances {
118-
go func(i instance) {
127+
e.Submit(func() {
119128
err := callback(i.desc, i.indexes)
120129
tracker.record(i, err)
121130
wg.Done()
122-
}(i)
131+
})
123132
}
124133

125134
// Perform cleanup at the end.

pkg/ring/ring_test.go

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,29 @@ func benchmarkBatch(b *testing.B, g TokenGenerator, numInstances, numKeys int) {
7373
}
7474
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
7575
keys := make([]uint32, numKeys)
76-
// Generate a batch of N random keys, and look them up
77-
b.ResetTimer()
78-
for i := 0; i < b.N; i++ {
79-
generateKeys(rnd, numKeys, keys)
80-
err := DoBatch(ctx, Write, &r, keys, callback, cleanup)
81-
require.NoError(b, err)
76+
77+
tc := map[string]struct {
78+
exe util.AsyncExecutor
79+
}{
80+
"noOpExecutor": {
81+
exe: noOpExecutor,
82+
},
83+
"workerExecutor": {
84+
exe: util.NewWorkerPool(100),
85+
},
86+
}
87+
88+
for n, c := range tc {
89+
b.Run(n, func(b *testing.B) {
90+
// Generate a batch of N random keys, and look them up
91+
b.ResetTimer()
92+
b.ReportAllocs()
93+
for i := 0; i < b.N; i++ {
94+
generateKeys(rnd, numKeys, keys)
95+
err := DoBatch(ctx, Write, &r, c.exe, keys, callback, cleanup)
96+
require.NoError(b, err)
97+
}
98+
})
8299
}
83100
}
84101

@@ -167,7 +184,7 @@ func TestDoBatchZeroInstances(t *testing.T) {
167184
ringDesc: desc,
168185
strategy: NewDefaultReplicationStrategy(),
169186
}
170-
require.Error(t, DoBatch(ctx, Write, &r, keys, callback, cleanup))
187+
require.Error(t, DoBatch(ctx, Write, &r, nil, keys, callback, cleanup))
171188
}
172189

173190
func TestAddIngester(t *testing.T) {

pkg/util/worker_pool.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package util
2+
3+
import "sync"
4+
5+
// This code was based on: https://github.com/grpc/grpc-go/blob/66ba4b264d26808cb7af3c86eee66e843472915e/server.go
6+
7+
// serverWorkerResetThreshold defines how often the stack must be reset. Every
8+
// N requests, by spawning a new goroutine in its place, a worker can reset its
9+
// stack so that large stacks don't live in memory forever. 2^16 should allow
10+
// each goroutine stack to live for at least a few seconds in a typical
11+
// workload (assuming a QPS of a few thousand requests/sec).
12+
const serverWorkerResetThreshold = 1 << 16
13+
14+
type AsyncExecutor interface {
15+
Submit(f func())
16+
}
17+
18+
type noOpExecutor struct{}
19+
20+
func NewNoOpExecutor() AsyncExecutor {
21+
return &noOpExecutor{}
22+
}
23+
24+
func (n noOpExecutor) Submit(f func()) {
25+
go f()
26+
}
27+
28+
type workerPoolExecutor struct {
29+
serverWorkerChannel chan func()
30+
closeOnce sync.Once
31+
}
32+
33+
func NewWorkerPool(numWorkers int) AsyncExecutor {
34+
wp := &workerPoolExecutor{
35+
serverWorkerChannel: make(chan func()),
36+
}
37+
38+
for i := 0; i < numWorkers; i++ {
39+
go wp.run()
40+
}
41+
42+
return wp
43+
}
44+
45+
func (s *workerPoolExecutor) Stop() {
46+
s.closeOnce.Do(func() {
47+
close(s.serverWorkerChannel)
48+
})
49+
}
50+
51+
func (s *workerPoolExecutor) Submit(f func()) {
52+
select {
53+
case s.serverWorkerChannel <- f:
54+
default:
55+
go f()
56+
}
57+
}
58+
59+
func (s *workerPoolExecutor) run() {
60+
for completed := 0; completed < serverWorkerResetThreshold; completed++ {
61+
f, ok := <-s.serverWorkerChannel
62+
if !ok {
63+
return
64+
}
65+
f()
66+
}
67+
go s.run()
68+
}

0 commit comments

Comments
 (0)