/
locking.go
308 lines (269 loc) · 8.92 KB
/
locking.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
package locking
import (
"errors"
"fmt"
"github.com/diggerhq/digger/libs/orchestrator"
"github.com/diggerhq/digger/pkg/aws"
"github.com/diggerhq/digger/pkg/aws/envprovider"
"github.com/diggerhq/digger/pkg/azure"
"github.com/diggerhq/digger/pkg/core/locking"
"github.com/diggerhq/digger/pkg/core/reporting"
"github.com/diggerhq/digger/pkg/core/utils"
"github.com/diggerhq/digger/pkg/gcp"
"log"
"os"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/service/sts"
"cloud.google.com/go/storage"
awssdk "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"
)
type PullRequestLock struct {
InternalLock locking.Lock
CIService orchestrator.PullRequestService
Reporter reporting.Reporter
ProjectName string
ProjectNamespace string
PrNumber int
}
type NoOpLock struct {
}
func (noOpLock *NoOpLock) Lock(transactionId int, resource string) (bool, error) {
return true, nil
}
func (noOpLock *NoOpLock) Unlock(resource string) (bool, error) {
return true, nil
}
func (noOpLock *NoOpLock) GetLock(resource string) (*int, error) {
return nil, nil
}
func (projectLock *PullRequestLock) Lock() (bool, error) {
lockId := projectLock.LockId()
log.Printf("Lock %s\n", lockId)
noHangingLocks, err := projectLock.verifyNoHangingLocks()
if err != nil {
return false, err
}
if !noHangingLocks {
return false, nil
}
existingLockTransactionId, err := projectLock.InternalLock.GetLock(lockId)
if err != nil {
log.Printf("failed to get lock: %v\n", err)
return false, err
}
if existingLockTransactionId != nil {
if *existingLockTransactionId == projectLock.PrNumber {
return true, nil
} else {
transactionIdStr := strconv.Itoa(*existingLockTransactionId)
comment := "Project " + projectLock.projectId() + " locked by another PR #" + transactionIdStr + " (failed to acquire lock " + projectLock.ProjectNamespace + "). The locking plan must be applied or discarded before future plans can execute"
reportLockingFailed(projectLock.Reporter, comment)
return false, nil
}
}
lockAcquired, err := projectLock.InternalLock.Lock(projectLock.PrNumber, lockId)
if err != nil {
return false, err
}
_, isNoOpLock := projectLock.InternalLock.(*NoOpLock)
if lockAcquired && !isNoOpLock {
comment := "Project " + projectLock.projectId() + " has been locked by PR #" + strconv.Itoa(projectLock.PrNumber)
reportingLockingSuccess(projectLock.Reporter, comment)
log.Println("project " + projectLock.projectId() + " locked successfully. PR # " + strconv.Itoa(projectLock.PrNumber))
}
return lockAcquired, nil
}
func reportingLockingSuccess(r reporting.Reporter, comment string) {
if r.SupportsMarkdown() {
err := r.Report(comment, utils.AsCollapsibleComment("Locking successful"))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
} else {
err := r.Report(comment, utils.AsComment("Locking successful"))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
}
}
func reportLockingFailed(r reporting.Reporter, comment string) {
if r.SupportsMarkdown() {
err := r.Report(comment, utils.AsCollapsibleComment("Locking failed"))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
} else {
err := r.Report(comment, utils.AsComment("Locking failed"))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
}
}
func (projectLock *PullRequestLock) verifyNoHangingLocks() (bool, error) {
lockId := projectLock.LockId()
transactionId, err := projectLock.InternalLock.GetLock(lockId)
if err != nil {
return false, err
}
if transactionId != nil {
if *transactionId != projectLock.PrNumber {
isPrClosed, err := projectLock.CIService.IsClosed(*transactionId)
if err != nil {
return false, fmt.Errorf("failed to check if PR holding a lock is closed: %w", err)
}
if isPrClosed {
_, err := projectLock.InternalLock.Unlock(lockId)
if err != nil {
return false, fmt.Errorf("failed to unlock a lock acquired by closed PR %v: %w", transactionId, err)
}
return true, nil
}
transactionIdStr := strconv.Itoa(*transactionId)
comment := "Project " + projectLock.projectId() + " locked by another PR #" + transactionIdStr + "(failed to acquire lock " + projectLock.ProjectName + "). The locking plan must be applied or discarded before future plans can execute"
reportLockingFailed(projectLock.Reporter, comment)
return false, nil
}
return true, nil
}
return true, nil
}
func (projectLock *PullRequestLock) Unlock() (bool, error) {
lockId := projectLock.LockId()
log.Printf("Unlock %s\n", lockId)
lock, err := projectLock.InternalLock.GetLock(lockId)
if err != nil {
return false, err
}
if lock != nil {
transactionId := *lock
if projectLock.PrNumber == transactionId {
lockReleased, err := projectLock.InternalLock.Unlock(lockId)
if err != nil {
return false, err
}
if lockReleased {
comment := "Project unlocked (" + projectLock.projectId() + ")."
reportSuccessfulUnlocking(projectLock.Reporter, comment)
log.Println("Project unlocked")
return true, nil
}
}
}
return false, nil
}
func reportSuccessfulUnlocking(r reporting.Reporter, comment string) {
if r.SupportsMarkdown() {
err := r.Report(comment, utils.AsCollapsibleComment("Unlocking successful"))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
} else {
err := r.Report(comment, utils.AsComment("Unlocking successful"))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
}
}
func (projectLock *PullRequestLock) ForceUnlock() error {
lockId := projectLock.LockId()
log.Printf("ForceUnlock %s\n", lockId)
lock, err := projectLock.InternalLock.GetLock(lockId)
if err != nil {
return err
}
if lock != nil {
lockReleased, err := projectLock.InternalLock.Unlock(lockId)
if err != nil {
return err
}
if lockReleased {
comment := "Project unlocked (" + projectLock.projectId() + ")."
reportSuccessfulUnlocking(projectLock.Reporter, comment)
log.Println("Project unlocked")
}
return nil
}
return nil
}
func (projectLock *PullRequestLock) projectId() string {
return projectLock.ProjectNamespace + "#" + projectLock.ProjectName
}
func (projectLock *PullRequestLock) LockId() string {
return projectLock.ProjectNamespace + "#" + projectLock.ProjectName
}
// DoEnvVarsExist return true if any of env vars do exist, false otherwise
func DoEnvVarsExist(envVars []string) bool {
result := false
for _, key := range envVars {
value := os.Getenv(key)
if value != "" {
result = true
}
}
return result
}
func GetLock() (locking.Lock, error) {
awsRegion := strings.ToLower(os.Getenv("AWS_REGION"))
awsProfile := strings.ToLower(os.Getenv("AWS_PROFILE"))
lockProvider := strings.ToLower(os.Getenv("LOCK_PROVIDER"))
disableLocking := strings.ToLower(os.Getenv("DISABLE_LOCKING")) == "true"
if disableLocking {
log.Println("Using NoOp lock provider.")
return &NoOpLock{}, nil
}
if lockProvider == "" || lockProvider == "aws" {
log.Println("Using AWS lock provider.")
// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html
options := session.Options{SharedConfigState: session.SharedConfigEnable}
keysToCheck := []string{"DIGGER_AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY"}
awsCredsProvided := DoEnvVarsExist(keysToCheck)
if awsCredsProvided {
options = session.Options{
Profile: awsProfile,
Config: awssdk.Config{
Region: awssdk.String(awsRegion),
Credentials: credentials.NewCredentials(&envprovider.EnvProvider{}),
},
}
} else {
log.Printf("Using keyless aws digger_config\n")
}
awsSession, err := session.NewSessionWithOptions(options)
if err != nil {
return nil, err
}
svc := sts.New(awsSession)
input := &sts.GetCallerIdentityInput{}
result, err := svc.GetCallerIdentity(input)
if err != nil {
return nil, fmt.Errorf("failed to connect to AWS account. %v\n", err)
}
log.Printf("Successfully connected to AWS account %s, user Id: %s\n", *result.Account, *result.UserId)
dynamoDb := dynamodb.New(awsSession)
dynamoDbLock := aws.DynamoDbLock{DynamoDb: dynamoDb}
return &dynamoDbLock, nil
} else if lockProvider == "gcp" {
log.Println("Using GCP lock provider.")
ctx, client := gcp.GetGoogleStorageClient()
defer func(client *storage.Client) {
err := client.Close()
if err != nil {
log.Fatalf("Failed to close Google Storage client: %v", err)
}
}(client)
bucketName := strings.ToLower(os.Getenv("GOOGLE_STORAGE_BUCKET"))
if bucketName == "" {
return nil, errors.New("GOOGLE_STORAGE_BUCKET is not set")
}
bucket := client.Bucket(bucketName)
lock := gcp.GoogleStorageLock{Client: client, Bucket: bucket, Context: ctx}
return &lock, nil
} else if lockProvider == "azure" {
return azure.NewStorageAccountLock()
}
return nil, errors.New("failed to find lock provider")
}