-
Notifications
You must be signed in to change notification settings - Fork 4
/
bitbucket.go
361 lines (282 loc) · 8.82 KB
/
bitbucket.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
package githosts
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"gitlab.com/tozd/go/errors"
"github.com/hashicorp/go-retryablehttp"
)
const (
BitbucketProviderName = "BitBucket"
bitbucketEnvVarKey = "BITBUCKET_KEY"
bitbucketEnvVarSecret = "BITBUCKET_SECRET"
bitbucketEnvVarUser = "BITBUCKET_USER"
bitbucketDomain = "bitbucket.com"
)
type NewBitBucketHostInput struct {
Caller string
HTTPClient *retryablehttp.Client
APIURL string
DiffRemoteMethod string
BackupDir string
User string
Key string
Secret string
BackupsToRetain int
LogLevel int
}
func NewBitBucketHost(input NewBitBucketHostInput) (*BitbucketHost, error) {
setLoggerPrefix(input.Caller)
apiURL := bitbucketAPIURL
if input.APIURL != "" {
apiURL = input.APIURL
}
diffRemoteMethod, err := getDiffRemoteMethod(input.DiffRemoteMethod)
if err != nil {
return nil, errors.Errorf("failed to get diff remote method: %s", err)
}
if diffRemoteMethod == "" {
logger.Print("using default diff remote method: " + defaultRemoteMethod)
diffRemoteMethod = defaultRemoteMethod
} else {
logger.Print("using diff remote method: " + diffRemoteMethod)
}
httpClient := input.HTTPClient
if httpClient == nil {
httpClient = getHTTPClient()
}
return &BitbucketHost{
HttpClient: httpClient,
Provider: BitbucketProviderName,
APIURL: apiURL,
DiffRemoteMethod: diffRemoteMethod,
BackupDir: input.BackupDir,
BackupsToRetain: input.BackupsToRetain,
User: input.User,
Key: input.Key,
Secret: input.Secret,
}, nil
}
func (bb BitbucketHost) auth(key, secret string) (string, error) {
b, _, _, err := httpRequest(httpRequestInput{
client: bb.HttpClient,
url: fmt.Sprintf("https://%s:%[email protected]/site/oauth2/access_token", key, secret),
method: http.MethodPost,
headers: http.Header{
"Host": []string{"bitbucket.org"},
"Content-Type": []string{"application/x-www-form-urlencoded"},
"Accept": []string{"*/*"},
},
reqBody: []byte("grant_type=client_credentials"),
basicAuthUser: key,
basicAuthPassword: secret,
secrets: []string{key, secret},
timeout: defaultHttpRequestTimeout,
})
if err != nil {
return "", errors.Errorf("failed to get bitbucket auth token: %s", err)
}
bodyStr := string(bytes.ReplaceAll(b, []byte("\r"), []byte("\r\n")))
var authResp bitbucketAuthResponse
if err = json.Unmarshal([]byte(bodyStr), &authResp); err != nil {
return "", errors.Errorf("failed to unmarshall bitbucket json response: %s", err)
}
// check for any errors
if authResp.AccessToken == "" {
var authErrResp bitbucketAuthErrorResponse
if err = json.Unmarshal([]byte(bodyStr), &authErrResp); err != nil {
return "", errors.Errorf("failed to unmarshall bitbucket json error response: %s", err)
}
return "", errors.Errorf("failed to get bitbucket auth token: %s - %s", authErrResp.Error, authErrResp.ErrorDescription)
}
return authResp.AccessToken, nil
}
type bitbucketAuthResponse struct {
AccessToken string `json:"access_token"`
Scopes string `json:"scopes"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
}
type bitbucketAuthErrorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
func (bb BitbucketHost) describeRepos() (describeReposOutput, errors.E) {
logger.Println("listing BitBucket repositories")
var err error
key := os.Getenv(bitbucketEnvVarKey)
secret := os.Getenv(bitbucketEnvVarSecret)
var token string
token, err = bb.auth(key, secret)
if err != nil {
return describeReposOutput{}, errors.Wrap(err, "failed to get bitbucket auth token")
}
var repos []repository
rawRequestURL := bb.APIURL + "/repositories?role=member"
ctx, cancel := context.WithTimeout(context.Background(), defaultHttpRequestTimeout)
defer cancel()
for {
req, errNewReq := retryablehttp.NewRequestWithContext(ctx, http.MethodGet, rawRequestURL, nil)
if errNewReq != nil {
logger.Println(errNewReq)
return describeReposOutput{}, errors.Wrap(errNewReq, "failed to create new request")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Set("Content-Type", contentTypeApplicationJSON)
req.Header.Set("Accept", contentTypeApplicationJSON)
var resp *http.Response
resp, err = bb.HttpClient.Do(req)
if err != nil {
logger.Println(err)
return describeReposOutput{}, errors.Wrap(err, "failed to make request")
}
var bodyB []byte
bodyB, err = io.ReadAll(resp.Body)
if err != nil {
return describeReposOutput{}, errors.Errorf("failed to read response body: %s", err)
}
bodyStr := string(bytes.ReplaceAll(bodyB, []byte("\r"), []byte("\r\n")))
_ = resp.Body.Close()
var respObj bitbucketGetProjectsResponse
if err = json.Unmarshal([]byte(bodyStr), &respObj); err != nil {
logger.Println(err)
return describeReposOutput{}, errors.Wrap(err, "failed to unmarshall bitbucket json response")
}
for _, r := range respObj.Values {
if r.Scm == "git" {
repo := repository{
Name: r.Name,
HTTPSUrl: "https://bitbucket.org/" + r.FullName + ".git",
PathWithNameSpace: r.FullName,
Domain: bitbucketDomain,
}
repos = append(repos, repo)
}
}
if respObj.Next != "" {
rawRequestURL = respObj.Next
continue
}
break
}
return describeReposOutput{
Repos: repos,
}, nil
}
func (bb BitbucketHost) getAPIURL() string {
return bb.APIURL
}
func bitBucketWorker(logLevel int, user, token, backupDIR, diffRemoteMethod string, backupsToKeep int, jobs <-chan repository, results chan<- RepoBackupResults) {
for repo := range jobs {
parts := strings.Split(repo.HTTPSUrl, "//")
repo.URLWithBasicAuth = parts[0] + "//" + user + ":" + token + "@" + parts[1]
err := processBackup(logLevel, repo, backupDIR, backupsToKeep, diffRemoteMethod)
backupResult := RepoBackupResults{
Repo: repo.PathWithNameSpace,
}
status := statusOk
if err != nil {
status = statusFailed
backupResult.Error = err
}
backupResult.Status = status
results <- backupResult
}
}
func (bb BitbucketHost) Backup() ProviderBackupResult {
if bb.BackupDir == "" {
logger.Printf("backup skipped as backup directory not specified")
return ProviderBackupResult{}
}
maxConcurrent := 5
var err error
var token string
token, err = bb.auth(bb.Key, bb.Secret)
if err != nil {
return ProviderBackupResult{
Error: errors.Errorf("failed to get bitbucket auth token: %s", err),
}
}
drO, err := bb.describeRepos()
if err != nil {
return ProviderBackupResult{}
}
jobs := make(chan repository, len(drO.Repos))
results := make(chan RepoBackupResults, maxConcurrent)
for w := 1; w <= maxConcurrent; w++ {
go bitBucketWorker(bb.LogLevel, bb.User, token, bb.BackupDir, bb.diffRemoteMethod(), bb.BackupsToRetain, jobs, results)
}
for x := range drO.Repos {
repo := drO.Repos[x]
jobs <- repo
}
close(jobs)
var providerBackupResults ProviderBackupResult
for a := 1; a <= len(drO.Repos); a++ {
res := <-results
if res.Error != nil {
logger.Printf("backup failed: %+v\n", res.Error)
providerBackupResults.Error = res.Error
return providerBackupResults
}
providerBackupResults.BackupResults = append(providerBackupResults.BackupResults, res)
}
return providerBackupResults
}
type BitbucketHost struct {
Caller string
HttpClient *retryablehttp.Client
Provider string
APIURL string
DiffRemoteMethod string
BackupDir string
BackupsToRetain int
User string
Key string
Secret string
LogLevel int
}
type bitbucketOwner struct {
DisplayName string `json:"display_name"`
}
type bitbucketProject struct {
Scm string `json:"scm"`
Owner bitbucketOwner
Name string `json:"name"`
FullName string `json:"full_name"`
IsPrivate bool `json:"is_private"`
Links bitbucketRepoLink `json:"links"`
}
type bitbucketCloneDetail struct {
Href string `json:"href"`
Name string `json:"name"`
}
type bitbucketRepoLink struct {
Clone []bitbucketCloneDetail `json:"clone"`
}
type bitbucketGetProjectsResponse struct {
Pagelen int `json:"pagelen"`
Values []bitbucketProject `json:"values"`
Next string `json:"next"`
}
// return normalised method.
func (bb BitbucketHost) diffRemoteMethod() string {
switch strings.ToLower(bb.DiffRemoteMethod) {
case refsMethod:
return refsMethod
case cloneMethod:
return cloneMethod
case "":
return cloneMethod
default:
logger.Printf("unexpected diff remote method: %s", bb.DiffRemoteMethod)
// default to bundle as safest
return cloneMethod
}
}