-
Notifications
You must be signed in to change notification settings - Fork 2
/
lock_dynamo.go
100 lines (83 loc) · 2.3 KB
/
lock_dynamo.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
package zpm
import (
"net/url"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
type DynamoLocker struct {
client *dynamodb.DynamoDB
tableName string
key string
}
func NewDynamoLocker(uri *url.URL) *DynamoLocker {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := dynamodb.New(sess)
tableName := uri.Host
key := uri.Path
return &DynamoLocker{
client: svc,
tableName: tableName,
key: key,
}
}
func (d *DynamoLocker) Lock() error {
_, err := d.LockWithEtag()
return err
}
// Unlock is used when we need to unlock repo but metadata wasn't changed
func (d *DynamoLocker) Unlock() error {
_, err := d.client.UpdateItem(&dynamodb.UpdateItemInput{
Key: map[string]*dynamodb.AttributeValue{
"LockKey": {S: aws.String(d.key)},
},
UpdateExpression: aws.String("SET Locked = :false"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":false": {BOOL: aws.Bool(false)},
},
TableName: &d.tableName,
})
return err
}
func (d *DynamoLocker) LockWithEtag() (string, error) {
eTag := ""
result, err := d.client.UpdateItem(&dynamodb.UpdateItemInput{
Key: map[string]*dynamodb.AttributeValue{
"LockKey": {S: aws.String(d.key)},
},
UpdateExpression: aws.String("SET Locked = :true"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":true": {BOOL: aws.Bool(true)},
":false": {BOOL: aws.Bool(false)},
},
ConditionExpression: aws.String("attribute_not_exists(Locked) or Locked = :false"),
ReturnValues: aws.String("ALL_NEW"),
TableName: &d.tableName,
})
if err != nil {
return eTag, err
}
if eTagResult, ok := result.Attributes["ETag"]; ok {
eTag = *eTagResult.S
}
return eTag, nil
}
func (d *DynamoLocker) UnlockWithEtag(eTag *string) error {
_, err := d.client.UpdateItem(&dynamodb.UpdateItemInput{
Key: map[string]*dynamodb.AttributeValue{
"LockKey": {S: aws.String(d.key)},
},
UpdateExpression: aws.String("SET Locked = :false, ETag = :eTag"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":false": {BOOL: aws.Bool(false)},
":eTag": {S: eTag},
},
TableName: &d.tableName,
})
if err != nil {
return err
}
return nil
}