-
Notifications
You must be signed in to change notification settings - Fork 4
/
goInterval_lock.go
362 lines (290 loc) · 9.33 KB
/
goInterval_lock.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
package gointerlock
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
"github.com/go-redis/redis/v8"
"github.com/lib/pq"
)
const Prefix = "GoInterLock"
const (
UniqueViolationErr = pq.ErrorCode("23505")
)
type Lock interface {
Lock(ctx context.Context, key string, interval time.Duration) (success bool, err error)
UnLock(ctx context.Context, key string) (err error)
SetClient() error
}
type RedisLocker struct {
redisConnector *redis.Client
// Name: is a unique job/task name, this is needed for distribution lock, this value enables the distribution mode. for local uses you don't need to set this value
Name string
// RedisHost Redis Host the default value "localhost:6379"
RedisHost string
// RedisPassword: Redis Password (AUTH), It can be blank if Redis has no authentication req
RedisPassword string
// 0 , It's from 0 to 15 (Not for redis cluster)
RedisDB string
}
func (r *RedisLocker) SetClient() error {
//already has connection
if r.redisConnector != nil {
return nil
}
log.Printf("Job %s started in distributed mode!", r.Name)
//if Redis host missed, use the default one
if r.RedisHost == "" {
r.RedisHost = "localhost:6379"
}
r.redisConnector = redis.NewClient(&redis.Options{
Addr: r.RedisHost,
Password: r.RedisPassword, // no password set
DB: 0, // use default DB
})
log.Printf("Job %s started in distributed mode by provided redis connection", r.Name)
return nil
}
func (r *RedisLocker) Lock(ctx context.Context, key string, lockTtl time.Duration) (success bool, err error) {
if r.redisConnector != nil {
if key == "" {
return false, errors.New("`Distributed Jobs should have a unique name!`")
}
res, err := r.redisConnector.SetNX(ctx, fmt.Sprintf("%s_%s", Prefix, key), time.Now().String(), lockTtl).Result()
if err != nil {
return false, err
}
return res, nil
}
return false, errors.New("`No Redis Connection found`")
}
func (r *RedisLocker) UnLock(ctx context.Context, key string) error {
if r.redisConnector != nil {
return r.redisConnector.Del(ctx, fmt.Sprintf("%s_%s", Prefix, key)).Err()
} else {
return nil
}
}
type DynamoDbLocker struct {
dynamoClient *dynamodb.DynamoDB
//leave empty to get from ~/.aws/credentials, (if AwsDynamoDbEndpoint not provided)
AwsDynamoDbRegion string
//leave empty to get from ~/.aws/credentials
AwsDynamoDbEndpoint string
//leave empty to get from ~/.aws/credentials, StaticCredentials (if AwsDynamoDbEndpoint not provided)
AwsDynamoDbAccessKeyID string
//leave empty to get from ~/.aws/credentials, StaticCredentials (if AwsDynamoDbEndpoint not provided)
AwsDynamoDbSecretAccessKey string
//leave empty to get from ~/.aws/credentials, StaticCredentials (if AwsDynamoDbEndpoint not provided)
AwsDynamoDbSessionToken string
}
func (d *DynamoDbLocker) SetClient() error {
// override the AWS profile credentials
if aws.String(d.AwsDynamoDbEndpoint) == nil {
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
// Create DynamoDB client
d.dynamoClient = dynamodb.New(sess)
} else {
if aws.String(d.AwsDynamoDbRegion) == nil {
return errors.New("`AwsDynamoDbRegion is missing (AWS Region)`")
}
//setting StaticCredentials
awsConfig := &aws.Config{
Credentials: credentials.NewStaticCredentials(d.AwsDynamoDbAccessKeyID, d.AwsDynamoDbSecretAccessKey, d.AwsDynamoDbSessionToken),
Region: aws.String(d.AwsDynamoDbRegion),
Endpoint: aws.String(d.AwsDynamoDbEndpoint),
}
sess, err := session.NewSession(awsConfig)
if err != nil {
return err
}
// Create DynamoDB client
d.dynamoClient = dynamodb.New(sess)
}
//sess, err := session.NewSession(&aws.Config{
// Region: aws.String("us-west-2"),
// Credentials: credentials.NewStaticCredentials(conf.AWS_ACCESS_KEY_ID, conf.AWS_SECRET_ACCESS_KEY, ""),
//})
if d.dynamoClient == nil {
return errors.New("`DynamoDb Connection Failed!`")
}
//check if table exist, if not create one
tableInput := &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("id"),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("id"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(10),
WriteCapacityUnits: aws.Int64(10),
},
//TimeToLiveDescription: &dynamodb.TimeToLiveDescription{
// AttributeName: aws.String("ttl"),
// TimeToLiveStatus: aws.String("enable"),
//},
TableName: aws.String(Prefix),
}
_, err := d.dynamoClient.CreateTable(tableInput)
if err != nil {
log.Printf("Got error calling CreateTable: %s", err)
} else {
fmt.Println("Created the table", Prefix)
}
return nil
}
func (d *DynamoDbLocker) Lock(ctx context.Context, key string, lockTtl time.Duration) (success bool, err error) {
if d.dynamoClient == nil {
return false, errors.New("`No Redis Connection found`")
}
expr, _ := expression.NewBuilder().WithFilter(
//filter by id
expression.Name("id").Equal(expression.Value(key)),
).Build()
// Build the query input parameters
params := &dynamodb.ScanInput{
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
FilterExpression: expr.Filter(),
TableName: aws.String(Prefix),
}
// Make the DynamoDB Query API call
result, _ := d.dynamoClient.ScanWithContext(ctx, params)
if len(result.Items) > 0 {
return false, nil
}
_, errPut := d.dynamoClient.PutItemWithContext(ctx, &dynamodb.PutItemInput{
Item: DynamoDbUnlockMarshal(key),
TableName: aws.String(Prefix),
})
if errPut != nil {
return false, errPut
}
return true, nil
}
func (d *DynamoDbLocker) UnLock(ctx context.Context, key string) error {
if d.dynamoClient != nil {
_, _ = d.dynamoClient.DeleteItemWithContext(ctx, &dynamodb.DeleteItemInput{
Key: DynamoDbUnlockMarshal(key),
TableName: aws.String(Prefix),
})
}
return nil
}
func DynamoDbUnlockMarshal(key string) map[string]*dynamodb.AttributeValue {
lockObj, _ := dynamodbattribute.MarshalMap(struct {
Id string `json:"id"`
}{
Id: key,
})
return lockObj
}
type PostgresLocker struct {
postgresConnector *sql.DB
// Name: is a unique job/task name, this is needed for distribution lock, this value enables the distribution mode. for local uses you don't need to set this value
Name string
// PostgresHost - Postgres Host the default value "localhost:5672"
PostgresHost string
// PostgresPassword: Redis Password (AUTH), It can be blank if Redis has no authentication req
PostgresPassword string
// 0 , It's from 0 to 15 (Not for redis cluster)
PostgresDB string
PostgresConnStr string
}
func (r *PostgresLocker) SetClient() error {
//already has connection
if r.postgresConnector != nil {
return nil
}
log.Printf("Job %s started in distributed mode!", r.Name)
//if Postgres host missed, use the default one
if r.PostgresHost == "" {
r.PostgresHost = "localhost:5432"
}
db, err := sql.Open("postgres", r.PostgresConnStr)
if err != nil {
log.Fatal(err)
}
r.postgresConnector = db
err = r.setupTable(db)
if err != nil {
log.Fatal(err)
}
log.Printf("Job %s started in distributed mode by provided postgres connection", r.Name)
return nil
}
func (r *PostgresLocker) setupTable(db *sql.DB) error {
query := `CREATE TABLE IF NOT EXISTS locks (
id text NOT NULL,
created_at timestamp NOT NULL,
ttl integer,
PRIMARY KEY (id)
)`
res, err := r.postgresConnector.ExecContext(context.Background(), query)
if err != nil {
return err
}
fmt.Print(res)
return nil
}
func (r *PostgresLocker) Lock(ctx context.Context, key string, lockTtl time.Duration) (success bool, err error) {
if r.postgresConnector != nil {
if key == "" {
return false, errors.New("`Distributed Jobs should have a unique name!`")
}
res, err := r.postgresConnector.ExecContext(ctx, "INSERT into locks values ($1,$2,$3)", fmt.Sprintf("%s_%s", Prefix, key), time.Now(), lockTtl.Seconds())
if err != nil {
if IsErrorCode(err, UniqueViolationErr) {
return false, nil
}
return false, err
}
affected, err := res.RowsAffected()
if err != nil {
return false, errors.New("`Couldn't Acquire Lock`")
}
return affected >= 1, nil
}
return false, errors.New("`No Postgres Connection found`")
}
func (r *PostgresLocker) UnLock(ctx context.Context, key string) error {
if r.postgresConnector != nil {
res, err := r.postgresConnector.ExecContext(ctx, "DELETE FROM locks WHERE id = $1", fmt.Sprintf("%s_%s", Prefix, key))
if err != nil {
return err
}
_, err = res.RowsAffected()
if err != nil {
return errors.New("`Couldn't Remove Lock`")
}
return nil
} else {
return nil
}
}
func IsErrorCode(err error, errcode pq.ErrorCode) bool {
if pgerr, ok := err.(*pq.Error); ok {
return pgerr.Code == errcode
}
return false
}