/
ddb_schemer.go
266 lines (223 loc) · 6.6 KB
/
ddb_schemer.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
package ddb
import (
"context"
. "github.com/cyberax/go-dd-service-base/visibility"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"strings"
"time"
)
type DynamoDbSchemer struct {
Suffix string
AwsConfig aws.Config
TestMode bool
}
func NewDynamoDbSchemer(suffix string, config aws.Config, testMode bool) *DynamoDbSchemer {
return &DynamoDbSchemer{
Suffix: suffix,
AwsConfig: config,
TestMode: testMode,
}
}
type Table struct {
Name string
HashKeyName string
RangeKeyName string
TtlFieldName string
GSI map[string]string
}
func (db *DynamoDbSchemer) InitSchema(ctx context.Context, tablesToCreate []Table) error {
CL(ctx).Info("Describing tables")
svc := dynamodb.New(db.AwsConfig)
var tables = make(map[string]int64)
lti := dynamodb.ListTablesInput{}
for {
output, err := svc.ListTablesRequest(<i).Send(ctx)
if err != nil {
return err
}
for _, t := range output.TableNames {
tables[strings.TrimSuffix(t, db.Suffix)] = 1
}
if output.LastEvaluatedTableName == nil {
break
}
lti.ExclusiveStartTableName = output.LastEvaluatedTableName
}
// Now create the missing tables
for _, t := range tablesToCreate {
if _, ok := tables[t.Name]; ok {
CLS(ctx).Infof("Table %s exists", t.Name)
err := db.ensureTtlIsSet(ctx, svc, t.Name+db.Suffix, t.TtlFieldName)
if err != nil {
return err
}
err = db.ensureGsiIsCreated(ctx, svc, t.Name+db.Suffix, t.GSI)
if err != nil {
return err
}
continue
}
newTableName := t.Name + db.Suffix
CLS(ctx).Infof("Creating table: %s", newTableName)
attrDefs := []dynamodb.AttributeDefinition{{
AttributeName: aws.String(t.HashKeyName), AttributeType: "S"},
}
keySchema := []dynamodb.KeySchemaElement{{
AttributeName: aws.String(t.HashKeyName), KeyType: "HASH",
}}
if t.RangeKeyName != "" {
attrDefs = append(attrDefs, dynamodb.AttributeDefinition{
AttributeName: aws.String(t.RangeKeyName), AttributeType: "S"})
keySchema = append(keySchema, dynamodb.KeySchemaElement{
AttributeName: aws.String(t.RangeKeyName), KeyType: "RANGE",
})
}
request := svc.CreateTableRequest(&dynamodb.CreateTableInput{
TableName: aws.String(newTableName),
AttributeDefinitions: attrDefs,
KeySchema: keySchema,
BillingMode: dynamodb.BillingModePayPerRequest,
ProvisionedThroughput: db.getDefIops(),
})
_, err := request.Send(ctx)
if err != nil {
return err
}
//noinspection GoUnhandledErrorResult
svc.WaitUntilTableExists(ctx, &dynamodb.DescribeTableInput{
TableName: aws.String(newTableName),
})
err = db.ensureTtlIsSet(ctx, svc, newTableName, t.TtlFieldName)
if err != nil {
return err
}
err = db.ensureGsiIsCreated(ctx, svc, newTableName, t.GSI)
if err != nil {
return err
}
}
CLS(ctx).Infof("All tables are ready")
return nil
}
func (db *DynamoDbSchemer) getDefIops() *dynamodb.ProvisionedThroughput {
var iops *dynamodb.ProvisionedThroughput
if db.TestMode {
iops = &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(100),
WriteCapacityUnits: aws.Int64(100),
}
}
return iops
}
func (db *DynamoDbSchemer) ensureTtlIsSet(ctx context.Context,
client *dynamodb.Client, tableName string, ttlField string) error {
if ttlField == "" {
return nil
}
response, err := client.DescribeTimeToLiveRequest(&dynamodb.DescribeTimeToLiveInput{
TableName: aws.String(tableName)}).Send(ctx)
if err != nil {
return err
}
if response.TimeToLiveDescription == nil ||
response.TimeToLiveDescription.TimeToLiveStatus == dynamodb.TimeToLiveStatusDisabled {
CLS(ctx).Infof("Setting TTL field on %s to %s", tableName, ttlField)
_, err := client.UpdateTimeToLiveRequest(&dynamodb.UpdateTimeToLiveInput{
TableName: aws.String(tableName),
TimeToLiveSpecification: &dynamodb.TimeToLiveSpecification{
AttributeName: aws.String(ttlField),
Enabled: aws.Bool(true),
},
}).Send(ctx)
if err != nil {
return err
}
CLS(ctx).Infof("Updated the TTL field on %s to %s", tableName, ttlField)
}
return nil
}
func (db *DynamoDbSchemer) ensureGsiIsCreated(ctx context.Context, client *dynamodb.Client,
tableName string, gsi map[string]string) error {
if gsi == nil || len(gsi) == 0 {
return nil
}
CLS(ctx).Infof("Checking the GSI for %s", tableName)
response, err := client.DescribeTableRequest(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
}).Send(ctx)
if err != nil {
return err
}
existing := make(map[string]int)
for _, i := range response.DescribeTableOutput.Table.GlobalSecondaryIndexes {
existing[*i.IndexName] = 1
}
var updates []dynamodb.GlobalSecondaryIndexUpdate
var attrDefs []dynamodb.AttributeDefinition
for idxName, idxColumn := range gsi {
if _, ok := existing[idxName]; ok {
CLS(ctx).Infof("GSI %s exists for %s", idxName, tableName)
continue
}
updates = append(updates, dynamodb.GlobalSecondaryIndexUpdate{
Create: &dynamodb.CreateGlobalSecondaryIndexAction{
IndexName: aws.String(idxName),
KeySchema: []dynamodb.KeySchemaElement{{
AttributeName: aws.String(idxColumn),
KeyType: dynamodb.KeyTypeHash,
}},
Projection: &dynamodb.Projection{
ProjectionType: dynamodb.ProjectionTypeAll,
},
ProvisionedThroughput: db.getDefIops(),
},
})
attrDefs = append(attrDefs, dynamodb.AttributeDefinition{
AttributeName: aws.String(idxColumn), AttributeType: "S"})
}
if len(updates) != 0 {
CLS(ctx).Infof("Creating GSIs for %s", tableName)
_, err := client.UpdateTableRequest(&dynamodb.UpdateTableInput{
TableName: aws.String(tableName),
GlobalSecondaryIndexUpdates: updates,
AttributeDefinitions: attrDefs,
}).Send(ctx)
if err != nil {
return err
}
}
err = db.waitForGsi(ctx, client, tableName)
if err != nil {
return err
}
CLS(ctx).Infof("GSI are up-to-date for %s", tableName)
return nil
}
func (db *DynamoDbSchemer) waitForGsi(ctx context.Context,
client *dynamodb.Client, tableName string) error {
// Wait for GSIs to be created
var hasPendingChanges = true
for ; hasPendingChanges; {
response, err := client.DescribeTableRequest(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
}).Send(ctx)
if err != nil {
return err
}
hasPendingChanges = false
for _, i := range response.DescribeTableOutput.Table.GlobalSecondaryIndexes {
if i.IndexStatus == dynamodb.IndexStatusCreating {
hasPendingChanges = true
// Wait a bit before the retry
select {
case <-ctx.Done():
return ctx.Err()
case <-time.NewTimer(2 * time.Second).C:
}
break
}
}
}
return nil
}