-
Notifications
You must be signed in to change notification settings - Fork 2
/
mutex.go
89 lines (72 loc) · 2.08 KB
/
mutex.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
package azmutex
import (
"context"
"fmt"
"github.com/Azure/azure-storage-blob-go/azblob"
)
type MutexOptions struct {
AccountName string
AccountKey string
ContainerName string
UseStorageEmulator bool
LogFunc func(message string)
}
type AzureMutex struct {
ctx context.Context
options MutexOptions
leaseId string
containerReference *azblob.ContainerURL
}
func NewMutex(options MutexOptions) *AzureMutex {
return NewMutexWithContext(options, context.Background())
}
func NewMutexWithContext(options MutexOptions, ctx context.Context) *AzureMutex {
return &AzureMutex{
options: options,
ctx: ctx,
}
}
func (m *AzureMutex) Acquire(key string, leaseDuration int32) error {
var err error
m.containerReference, err = m.createContainerURL()
if err != nil {
return err
}
err = m.createContainerIfNotExists()
if err != nil {
return err
}
blob := m.containerReference.NewBlockBlobURL(key)
_, err = azblob.UploadBufferToBlockBlob(m.ctx, []byte{}, blob, azblob.UploadToBlockBlobOptions{})
if stgErr, ok := err.(azblob.StorageError); ok && stgErr.ServiceCode() == "LeaseIdMissing" {
return NewLeaseAlreadyPresentError(err)
}
if err != nil {
return err
}
response, err := blob.AcquireLease(m.ctx, "", leaseDuration, azblob.ModifiedAccessConditions{})
if stgErr, ok := err.(azblob.StorageError); ok && stgErr.ServiceCode() == "LeaseAlreadyPresent" {
return NewLeaseAlreadyPresentError(err)
}
if err != nil {
return err
}
m.leaseId = response.LeaseID()
return nil
}
func (m *AzureMutex) Renew(key string) error {
if m.containerReference == nil {
return fmt.Errorf("lock not aquired")
}
blob := m.containerReference.NewBlockBlobURL(key)
_, err := blob.RenewLease(m.ctx, m.leaseId, azblob.ModifiedAccessConditions{})
return err
}
func (m *AzureMutex) Release(key string) error {
if m.containerReference == nil {
return fmt.Errorf("lock not aquired")
}
blob := m.containerReference.NewBlockBlobURL(key)
_, err := blob.ReleaseLease(m.ctx, m.leaseId, azblob.ModifiedAccessConditions{})
return err
}