-
Notifications
You must be signed in to change notification settings - Fork 790
/
ring.go
368 lines (319 loc) · 9.5 KB
/
ring.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package ring
// Based on https://raw.githubusercontent.com/stathat/consistent/master/consistent.go
import (
"context"
"errors"
"flag"
"fmt"
"math"
"sort"
"sync"
"time"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/cortexproject/cortex/pkg/ring/kv"
"github.com/cortexproject/cortex/pkg/ring/kv/codec"
"github.com/cortexproject/cortex/pkg/util"
)
const (
unhealthy = "Unhealthy"
// ConsulKey is the key under which we store the ring in consul.
ConsulKey = "ring"
)
// ReadRing represents the read inferface to the ring.
type ReadRing interface {
prometheus.Collector
// Get returns n (or more) ingesters which form the replicas for the given key.
// buf is a slice to be overwritten for the return value
// to avoid memory allocation; can be nil.
Get(key uint32, op Operation, buf []IngesterDesc) (ReplicationSet, error)
GetAll() (ReplicationSet, error)
ReplicationFactor() int
IngesterCount() int
}
// Operation can be Read or Write
type Operation int
// Values for Operation
const (
Read Operation = iota
Write
Reporting // Special value for inquiring about health
)
type uint32s []uint32
func (x uint32s) Len() int { return len(x) }
func (x uint32s) Less(i, j int) bool { return x[i] < x[j] }
func (x uint32s) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
// ErrEmptyRing is the error returned when trying to get an element when nothing has been added to hash.
var ErrEmptyRing = errors.New("empty ring")
// Config for a Ring
type Config struct {
KVStore kv.Config `yaml:"kvstore,omitempty"`
HeartbeatTimeout time.Duration `yaml:"heartbeat_timeout,omitempty"`
ReplicationFactor int `yaml:"replication_factor,omitempty"`
}
// RegisterFlags adds the flags required to config this to the given FlagSet with a specified prefix
func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
cfg.RegisterFlagsWithPrefix("", f)
}
// RegisterFlagsWithPrefix adds the flags required to config this to the given FlagSet with a specified prefix
func (cfg *Config) RegisterFlagsWithPrefix(prefix string, f *flag.FlagSet) {
cfg.KVStore.RegisterFlagsWithPrefix(prefix, f)
f.DurationVar(&cfg.HeartbeatTimeout, prefix+"ring.heartbeat-timeout", time.Minute, "The heartbeat timeout after which ingesters are skipped for reads/writes.")
f.IntVar(&cfg.ReplicationFactor, prefix+"distributor.replication-factor", 3, "The number of ingesters to write to and read from.")
}
// Ring holds the information about the members of the consistent hash ring.
type Ring struct {
name string
cfg Config
KVClient kv.Client
done chan struct{}
quit context.CancelFunc
mtx sync.RWMutex
ringDesc *Desc
memberOwnershipDesc *prometheus.Desc
numMembersDesc *prometheus.Desc
totalTokensDesc *prometheus.Desc
numTokensDesc *prometheus.Desc
}
// New creates a new Ring
func New(cfg Config, name string) (*Ring, error) {
if cfg.ReplicationFactor <= 0 {
return nil, fmt.Errorf("ReplicationFactor must be greater than zero: %d", cfg.ReplicationFactor)
}
codec := codec.Proto{Factory: ProtoDescFactory}
store, err := kv.NewClient(cfg.KVStore, codec)
if err != nil {
return nil, err
}
r := &Ring{
name: name,
cfg: cfg,
KVClient: store,
done: make(chan struct{}),
ringDesc: &Desc{},
memberOwnershipDesc: prometheus.NewDesc(
"cortex_ring_member_ownership_percent",
"The percent ownership of the ring by member",
[]string{"member", "name"}, nil,
),
numMembersDesc: prometheus.NewDesc(
"cortex_ring_members",
"Number of members in the ring",
[]string{"state", "name"}, nil,
),
totalTokensDesc: prometheus.NewDesc(
"cortex_ring_tokens_total",
"Number of tokens in the ring",
[]string{"name"}, nil,
),
numTokensDesc: prometheus.NewDesc(
"cortex_ring_tokens_owned",
"The number of tokens in the ring owned by the member",
[]string{"member", "name"}, nil,
),
}
var ctx context.Context
ctx, r.quit = context.WithCancel(context.Background())
go r.loop(ctx)
return r, nil
}
// Stop the distributor.
func (r *Ring) Stop() {
r.quit()
<-r.done
}
func (r *Ring) loop(ctx context.Context) {
defer close(r.done)
r.KVClient.WatchKey(ctx, ConsulKey, func(value interface{}) bool {
if value == nil {
level.Info(util.Logger).Log("msg", "ring doesn't exist in consul yet")
return true
}
ringDesc := value.(*Desc)
ringDesc.Tokens = migrateRing(ringDesc)
r.mtx.Lock()
defer r.mtx.Unlock()
r.ringDesc = ringDesc
return true
})
}
// migrateRing will denormalise the ring's tokens if stored in normal form.
func migrateRing(desc *Desc) []TokenDesc {
numTokens := len(desc.Tokens)
for _, ing := range desc.Ingesters {
numTokens += len(ing.Tokens)
}
tokens := make([]TokenDesc, len(desc.Tokens), numTokens)
copy(tokens, desc.Tokens)
for key, ing := range desc.Ingesters {
for _, token := range ing.Tokens {
tokens = append(tokens, TokenDesc{
Token: token,
Ingester: key,
})
}
}
sort.Sort(ByToken(tokens))
return tokens
}
// Get returns n (or more) ingesters which form the replicas for the given key.
func (r *Ring) Get(key uint32, op Operation, buf []IngesterDesc) (ReplicationSet, error) {
r.mtx.RLock()
defer r.mtx.RUnlock()
if r.ringDesc == nil || len(r.ringDesc.Tokens) == 0 {
return ReplicationSet{}, ErrEmptyRing
}
var (
n = r.cfg.ReplicationFactor
ingesters = buf[:0]
distinctHosts = map[string]struct{}{}
start = r.search(key)
iterations = 0
)
for i := start; len(distinctHosts) < n && iterations < len(r.ringDesc.Tokens); i++ {
iterations++
// Wrap i around in the ring.
i %= len(r.ringDesc.Tokens)
// We want n *distinct* ingesters.
token := r.ringDesc.Tokens[i]
if _, ok := distinctHosts[token.Ingester]; ok {
continue
}
distinctHosts[token.Ingester] = struct{}{}
ingester := r.ringDesc.Ingesters[token.Ingester]
// We do not want to Write to Ingesters that are not ACTIVE, but we do want
// to write the extra replica somewhere. So we increase the size of the set
// of replicas for the key. This means we have to also increase the
// size of the replica set for read, but we can read from Leaving ingesters,
// so don't skip it in this case.
// NB dead ingester will be filtered later (by replication_strategy.go).
if op == Write && ingester.State != ACTIVE {
n++
} else if op == Read && (ingester.State != ACTIVE && ingester.State != LEAVING) {
n++
}
ingesters = append(ingesters, ingester)
}
liveIngesters, maxFailure, err := r.replicationStrategy(ingesters, op)
if err != nil {
return ReplicationSet{}, err
}
return ReplicationSet{
Ingesters: liveIngesters,
MaxErrors: maxFailure,
}, nil
}
// GetAll returns all available ingesters in the ring.
func (r *Ring) GetAll() (ReplicationSet, error) {
r.mtx.RLock()
defer r.mtx.RUnlock()
if r.ringDesc == nil || len(r.ringDesc.Tokens) == 0 {
return ReplicationSet{}, ErrEmptyRing
}
ingesters := make([]IngesterDesc, 0, len(r.ringDesc.Ingesters))
maxErrors := r.cfg.ReplicationFactor / 2
for _, ingester := range r.ringDesc.Ingesters {
if !r.IsHealthy(&ingester, Read) {
maxErrors--
continue
}
ingesters = append(ingesters, ingester)
}
if maxErrors < 0 {
return ReplicationSet{}, fmt.Errorf("too many failed ingesters")
}
return ReplicationSet{
Ingesters: ingesters,
MaxErrors: maxErrors,
}, nil
}
func (r *Ring) search(key uint32) int {
i := sort.Search(len(r.ringDesc.Tokens), func(x int) bool {
return r.ringDesc.Tokens[x].Token > key
})
if i >= len(r.ringDesc.Tokens) {
i = 0
}
return i
}
// Describe implements prometheus.Collector.
func (r *Ring) Describe(ch chan<- *prometheus.Desc) {
ch <- r.memberOwnershipDesc
ch <- r.numMembersDesc
ch <- r.totalTokensDesc
ch <- r.numTokensDesc
}
func countTokens(ringDesc *Desc) (map[string]uint32, map[string]uint32) {
tokens := ringDesc.Tokens
owned := map[string]uint32{}
numTokens := map[string]uint32{}
for i, token := range tokens {
var diff uint32
if i+1 == len(tokens) {
diff = (math.MaxUint32 - token.Token) + tokens[0].Token
} else {
diff = tokens[i+1].Token - token.Token
}
numTokens[token.Ingester] = numTokens[token.Ingester] + 1
owned[token.Ingester] = owned[token.Ingester] + diff
}
for id := range ringDesc.Ingesters {
if _, ok := owned[id]; !ok {
owned[id] = 0
numTokens[id] = 0
}
}
return numTokens, owned
}
// Collect implements prometheus.Collector.
func (r *Ring) Collect(ch chan<- prometheus.Metric) {
r.mtx.RLock()
defer r.mtx.RUnlock()
numTokens, ownedRange := countTokens(r.ringDesc)
for id, totalOwned := range ownedRange {
ch <- prometheus.MustNewConstMetric(
r.memberOwnershipDesc,
prometheus.GaugeValue,
float64(totalOwned)/float64(math.MaxUint32),
id,
r.name,
)
ch <- prometheus.MustNewConstMetric(
r.numTokensDesc,
prometheus.GaugeValue,
float64(numTokens[id]),
id,
r.name,
)
}
// Initialised to zero so we emit zero-metrics (instead of not emitting anything)
byState := map[string]int{
unhealthy: 0,
ACTIVE.String(): 0,
LEAVING.String(): 0,
PENDING.String(): 0,
JOINING.String(): 0,
}
for _, ingester := range r.ringDesc.Ingesters {
if !r.IsHealthy(&ingester, Reporting) {
byState[unhealthy]++
} else {
byState[ingester.State.String()]++
}
}
for state, count := range byState {
ch <- prometheus.MustNewConstMetric(
r.numMembersDesc,
prometheus.GaugeValue,
float64(count),
state,
r.name,
)
}
ch <- prometheus.MustNewConstMetric(
r.totalTokensDesc,
prometheus.GaugeValue,
float64(len(r.ringDesc.Tokens)),
r.name,
)
}