forked from cortexproject/cortex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table_manager.go
331 lines (278 loc) · 8.89 KB
/
table_manager.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
package chunk
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/weaveworks/common/instrument"
"github.com/weaveworks/common/mtime"
"github.com/weaveworks/cortex/pkg/util"
)
const (
readLabel = "read"
writeLabel = "write"
)
var (
syncTableDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "cortex",
Name: "dynamo_sync_tables_seconds",
Help: "Time spent doing SyncTables.",
Buckets: prometheus.DefBuckets,
}, []string{"operation", "status_code"})
tableCapacity = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "cortex",
Name: "dynamo_table_capacity_units",
Help: "Per-table DynamoDB capacity, measured in DynamoDB capacity units.",
}, []string{"op", "table"})
)
func init() {
prometheus.MustRegister(tableCapacity)
prometheus.MustRegister(syncTableDuration)
}
// Tags is a string-string map that implements flag.Value.
type Tags map[string]string
// String implements flag.Value
func (ts Tags) String() string {
if ts == nil {
return ""
}
return fmt.Sprintf("%v", map[string]string(ts))
}
// Set implements flag.Value
func (ts *Tags) Set(s string) error {
if *ts == nil {
*ts = map[string]string{}
}
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
return fmt.Errorf("tag must of the format key=value")
}
(*ts)[parts[0]] = parts[1]
return nil
}
// Equals returns true is other matches ts.
func (ts Tags) Equals(other Tags) bool {
if len(ts) != len(other) {
return false
}
for k, v1 := range ts {
v2, ok := other[k]
if !ok || v1 != v2 {
return false
}
}
return true
}
// AWSTags converts ts into a []*dynamodb.Tag.
func (ts Tags) AWSTags() []*dynamodb.Tag {
if ts == nil {
return nil
}
var result []*dynamodb.Tag
for k, v := range ts {
result = append(result, &dynamodb.Tag{
Key: aws.String(k),
Value: aws.String(v),
})
}
return result
}
// TableManager creates and manages the provisioned throughput on DynamoDB tables
type TableManager struct {
client TableClient
cfg SchemaConfig
maxChunkAge time.Duration
done chan struct{}
wait sync.WaitGroup
}
// NewTableManager makes a new TableManager
func NewTableManager(cfg SchemaConfig, maxChunkAge time.Duration, tableClient TableClient) (*TableManager, error) {
return &TableManager{
cfg: cfg,
maxChunkAge: maxChunkAge,
client: tableClient,
done: make(chan struct{}),
}, nil
}
// Start the TableManager
func (m *TableManager) Start() {
m.wait.Add(1)
go m.loop()
}
// Stop the TableManager
func (m *TableManager) Stop() {
close(m.done)
m.wait.Wait()
}
func (m *TableManager) loop() {
defer m.wait.Done()
ticker := time.NewTicker(m.cfg.DynamoDBPollInterval)
defer ticker.Stop()
if err := instrument.TimeRequestHistogram(context.Background(), "TableManager.SyncTables", syncTableDuration, func(ctx context.Context) error {
return m.SyncTables(ctx)
}); err != nil {
level.Error(util.Logger).Log("msg", "error syncing tables", "err", err)
}
for {
select {
case <-ticker.C:
if err := instrument.TimeRequestHistogram(context.Background(), "TableManager.SyncTables", syncTableDuration, func(ctx context.Context) error {
return m.SyncTables(ctx)
}); err != nil {
level.Error(util.Logger).Log("msg", "error syncing tables", "err", err)
}
case <-m.done:
return
}
}
}
// SyncTables will calculate the tables expected to exist, create those that do
// not and update those that need it. It is exposed for testing.
func (m *TableManager) SyncTables(ctx context.Context) error {
expected := m.calculateExpectedTables()
level.Info(util.Logger).Log("msg", "synching tables", "num_expected_tables", len(expected), "expected_tables", expected)
toCreate, toCheckThroughput, err := m.partitionTables(ctx, expected)
if err != nil {
return err
}
if err := m.createTables(ctx, toCreate); err != nil {
return err
}
return m.updateTables(ctx, toCheckThroughput)
}
func (m *TableManager) calculateExpectedTables() []TableDesc {
result := []TableDesc{}
// Add the legacy table
legacyTable := TableDesc{
Name: m.cfg.OriginalTableName,
ProvisionedRead: m.cfg.IndexTables.InactiveReadThroughput,
ProvisionedWrite: m.cfg.IndexTables.InactiveWriteThroughput,
Tags: m.cfg.IndexTables.GetTags(),
}
if m.cfg.UsePeriodicTables {
// if we are before the switch to periodic table, we need to give this table write throughput
var (
tablePeriodSecs = int64(m.cfg.IndexTables.Period / time.Second)
gracePeriodSecs = int64(m.cfg.CreationGracePeriod / time.Second)
maxChunkAgeSecs = int64(m.maxChunkAge / time.Second)
firstTable = m.cfg.IndexTables.From.Unix() / tablePeriodSecs
now = mtime.Now().Unix()
)
if now < (firstTable*tablePeriodSecs)+gracePeriodSecs+maxChunkAgeSecs {
legacyTable.ProvisionedRead = m.cfg.IndexTables.ProvisionedReadThroughput
legacyTable.ProvisionedWrite = m.cfg.IndexTables.ProvisionedWriteThroughput
if m.cfg.IndexTables.WriteScale.Enabled {
legacyTable.WriteScale = m.cfg.IndexTables.WriteScale
}
}
}
result = append(result, legacyTable)
if m.cfg.UsePeriodicTables {
result = append(result, m.cfg.IndexTables.periodicTables(
m.cfg.CreationGracePeriod, m.maxChunkAge,
)...)
}
if m.cfg.ChunkTables.From.IsSet() {
result = append(result, m.cfg.ChunkTables.periodicTables(
m.cfg.CreationGracePeriod, m.maxChunkAge,
)...)
}
sort.Sort(byName(result))
return result
}
// partitionTables works out tables that need to be created vs tables that need to be updated
func (m *TableManager) partitionTables(ctx context.Context, descriptions []TableDesc) ([]TableDesc, []TableDesc, error) {
existingTables, err := m.client.ListTables(ctx)
if err != nil {
return nil, nil, err
}
sort.Strings(existingTables)
toCreate, toCheck := []TableDesc{}, []TableDesc{}
i, j := 0, 0
for i < len(descriptions) && j < len(existingTables) {
if descriptions[i].Name < existingTables[j] {
// Table descriptions[i] doesn't exist
toCreate = append(toCreate, descriptions[i])
i++
} else if descriptions[i].Name > existingTables[j] {
// existingTables[j].name isn't in descriptions, can ignore
j++
} else {
// Table exists, need to check it has correct throughput
toCheck = append(toCheck, descriptions[i])
i++
j++
}
}
for ; i < len(descriptions); i++ {
toCreate = append(toCreate, descriptions[i])
}
return toCreate, toCheck, nil
}
func (m *TableManager) createTables(ctx context.Context, descriptions []TableDesc) error {
for _, desc := range descriptions {
level.Info(util.Logger).Log("msg", "creating table", "table", desc.Name)
err := m.client.CreateTable(ctx, desc)
if err != nil {
return err
}
}
return nil
}
func (m *TableManager) updateTables(ctx context.Context, descriptions []TableDesc) error {
for _, expected := range descriptions {
level.Info(util.Logger).Log("msg", "checking provisioned throughput on table", "table", expected.Name)
current, status, err := m.client.DescribeTable(ctx, expected.Name)
if err != nil {
return err
}
if status != dynamodb.TableStatusActive {
level.Info(util.Logger).Log("msg", "skipping update on table, not yet ACTIVE", "table", expected.Name, "status", status)
continue
}
tableCapacity.WithLabelValues(readLabel, expected.Name).Set(float64(current.ProvisionedRead))
tableCapacity.WithLabelValues(writeLabel, expected.Name).Set(float64(current.ProvisionedWrite))
if expected.Equals(current) {
level.Info(util.Logger).Log("msg", "provisioned throughput on table, skipping", "table", current.Name, "read", current.ProvisionedRead, "write", current.ProvisionedWrite)
continue
}
level.Info(util.Logger).Log("msg", "updating provisioned throughput on table", "table", expected.Name, "old_read", current.ProvisionedRead, "old_write", current.ProvisionedWrite, "new_read", expected.ProvisionedRead, "old_read", expected.ProvisionedWrite)
err = m.client.UpdateTable(ctx, current, expected)
if err != nil {
return err
}
}
return nil
}
// ExpectTables compares existing tables to an expected set of tables. Exposed
// for testing,
func ExpectTables(ctx context.Context, client TableClient, expected []TableDesc) error {
tables, err := client.ListTables(ctx)
if err != nil {
return err
}
if len(expected) != len(tables) {
return fmt.Errorf("Unexpected number of tables: %v != %v", expected, tables)
}
sort.Strings(tables)
sort.Sort(byName(expected))
for i, expect := range expected {
if tables[i] != expect.Name {
return fmt.Errorf("Expected '%s', found '%s'", expect.Name, tables[i])
}
desc, _, err := client.DescribeTable(ctx, expect.Name)
if err != nil {
return err
}
if !desc.Equals(expect) {
return fmt.Errorf("Expected '%v', found '%v' for table '%s'", expect, desc, desc.Name)
}
}
return nil
}