-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
440 lines (390 loc) · 11.5 KB
/
client.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package bitbucketcloud
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
"github.com/rancher/norman/httperror"
"github.com/rancher/rancher/pkg/pipeline/remote/model"
"github.com/rancher/rancher/pkg/pipeline/utils"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/rancher/pkg/settings"
"github.com/rancher/types/apis/project.cattle.io/v3"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
)
const (
apiEndpoint = "https://api.bitbucket.org/2.0"
authURL = "https://bitbucket.org/site/oauth2/authorize"
tokenURL = "https://bitbucket.org/site/oauth2/access_token"
maxPerPage = "100"
cloneUserName = "x-token-auth"
)
type client struct {
ClientID string
ClientSecret string
RedirectURL string
}
func New(config *v3.BitbucketCloudPipelineConfig) (model.Remote, error) {
if config == nil {
return nil, errors.New("empty gitlab config")
}
glClient := &client{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
RedirectURL: config.RedirectURL,
}
return glClient, nil
}
func (c *client) Type() string {
return model.BitbucketCloudType
}
func (c *client) Login(code string) (*v3.SourceCodeCredential, error) {
oauthConfig := &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
RedirectURL: c.RedirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
}
token, err := oauthConfig.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
} else if token.TokenType != "bearer" || token.AccessToken == "" {
return nil, fmt.Errorf("Fail to get accesstoken with oauth config")
}
user, err := c.getUser(token.AccessToken)
if err != nil {
return nil, err
}
cred := convertUser(user)
cred.Spec.AccessToken = token.AccessToken
cred.Spec.RefreshToken = token.RefreshToken
cred.Spec.Expiry = token.Expiry.Format(time.RFC3339)
return cred, nil
}
func (c *client) Repos(account *v3.SourceCodeCredential) ([]v3.SourceCodeRepository, error) {
if account == nil {
return nil, fmt.Errorf("empty account")
}
nexturl := apiEndpoint + "/repositories?role=admin"
var repos []Repository
for nexturl != "" {
b, err := getFromBitbucket(nexturl, account.Spec.AccessToken)
if err != nil {
return nil, err
}
var pageRepos PaginatedRepositories
if err := json.Unmarshal(b, &pageRepos); err != nil {
return nil, err
}
nexturl = pageRepos.Next
repos = append(repos, pageRepos.Values...)
}
return convertRepos(repos), nil
}
func (c *client) CreateHook(pipeline *v3.Pipeline, accessToken string) (string, error) {
user, repo, err := getUserRepoFromURL(pipeline.Spec.RepositoryURL)
if err != nil {
return "", err
}
hookURL := fmt.Sprintf("%s/hooks?pipelineId=%s", settings.ServerURL.Get(), ref.Ref(pipeline))
hook := Hook{
Description: "Webhook created by Rancher Pipeline",
URL: hookURL,
Active: true,
SkipCertVerification: true,
Events: []string{
"repo:push",
"pullrequest:updated",
"pullrequest:created",
},
}
url := fmt.Sprintf("%s/repositories/%s/%s/hooks", apiEndpoint, user, repo)
b, err := json.Marshal(hook)
if err != nil {
return "", err
}
reader := bytes.NewReader(b)
resp, err := doRequestToBitbucket(http.MethodPost, url, accessToken, nil, reader)
if err != nil {
return "", err
}
err = json.Unmarshal(resp, &hook)
if err != nil {
return "", err
}
return hook.UUID, nil
}
func (c *client) DeleteHook(pipeline *v3.Pipeline, accessToken string) error {
user, repo, err := getUserRepoFromURL(pipeline.Spec.RepositoryURL)
if err != nil {
return err
}
hook, err := c.getHook(pipeline, accessToken)
if err != nil {
return err
}
if hook != nil {
url := fmt.Sprintf("%s/repositories/%s/%s/hooks/%v", apiEndpoint, user, repo, hook.UUID)
_, err := doRequestToBitbucket(http.MethodDelete, url, accessToken, nil, nil)
if err != nil {
return err
}
}
return nil
}
func (c *client) getHook(pipeline *v3.Pipeline, accessToken string) (*Hook, error) {
user, repo, err := getUserRepoFromURL(pipeline.Spec.RepositoryURL)
if err != nil {
return nil, err
}
var hooks PaginatedHooks
var result *Hook
url := fmt.Sprintf("%s/repositories/%s/%s/hooks", apiEndpoint, user, repo)
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &hooks); err != nil {
return nil, err
}
for _, hook := range hooks.Values {
if strings.HasSuffix(hook.URL, fmt.Sprintf("hooks?pipelineId=%s", ref.Ref(pipeline))) {
result = &hook
break
}
}
return result, nil
}
func (c *client) getFileFromRepo(filename string, owner string, repo string, branch string, accessToken string) ([]byte, error) {
url := fmt.Sprintf("%s/repositories/%s/%s/src/%s/%s", apiEndpoint, owner, repo, branch, filename)
return getFromBitbucket(url, accessToken)
}
func (c *client) GetPipelineFileInRepo(repoURL string, branch string, accessToken string) ([]byte, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
content, err := c.getFileFromRepo(utils.PipelineFileYaml, owner, repo, branch, accessToken)
if err != nil {
//look for both suffix
content, err = c.getFileFromRepo(utils.PipelineFileYml, owner, repo, branch, accessToken)
}
if err != nil {
logrus.Debugf("error GetPipelineFileInRepo - %v", err)
return nil, nil
}
return content, nil
}
func (c *client) SetPipelineFileInRepo(repoURL string, branch string, accessToken string, content []byte) error {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return err
}
currentContent, err := c.getFileFromRepo(utils.PipelineFileYml, owner, repo, branch, accessToken)
currentFileName := utils.PipelineFileYml
if err != nil {
if httpErr, ok := err.(*httperror.APIError); !ok || httpErr.Code.Status != http.StatusNotFound {
return err
}
//look for both suffix
currentContent, err = c.getFileFromRepo(utils.PipelineFileYaml, owner, repo, branch, accessToken)
if err != nil {
if httpErr, ok := err.(*httperror.APIError); !ok || httpErr.Code.Status != http.StatusNotFound {
return err
}
} else {
currentFileName = utils.PipelineFileYaml
}
}
apiurl := fmt.Sprintf("%s/repositories/%s/%s/src", apiEndpoint, owner, repo)
message := "Create .rancher-pipeline.yml file"
if currentContent != nil {
//update pipeline file
message = fmt.Sprintf("Update %s file", currentFileName)
}
data := url.Values{}
data.Set("message", message)
data.Set("branch", branch)
data.Set(currentFileName, string(content))
data.Encode()
reader := strings.NewReader(data.Encode())
header := map[string]string{"Content-Type": "application/x-www-form-urlencoded"}
_, err = doRequestToBitbucket(http.MethodPost, apiurl, accessToken, header, reader)
return err
}
func (c *client) GetBranches(repoURL string, accessToken string) ([]string, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/repositories/%s/%s/refs/branches", apiEndpoint, owner, repo)
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
var branches PaginatedBranches
if err := json.Unmarshal(b, &branches); err != nil {
return nil, err
}
result := []string{}
for _, b := range branches.Values {
result = append(result, b.Name)
}
return result, nil
}
func (c *client) GetHeadInfo(repoURL string, branch string, accessToken string) (*model.BuildInfo, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/repositories/%s/%s/refs/branches/%s", apiEndpoint, owner, repo, branch)
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
var branchObj Ref
if err := json.Unmarshal(b, &branchObj); err != nil {
return nil, err
}
info := &model.BuildInfo{}
info.Commit = branchObj.Target.Hash
info.Ref = branch
info.Branch = branch
info.Message = branchObj.Target.Message
info.HTMLLink = branchObj.Links.HTML.Href
info.AvatarURL = branchObj.Target.Author.User.Links.Avatar.Href
info.Author = branchObj.Target.Author.User.UserName
return info, nil
}
func convertUser(bitbucketUser *User) *v3.SourceCodeCredential {
if bitbucketUser == nil {
return nil
}
cred := &v3.SourceCodeCredential{}
cred.Spec.SourceCodeType = model.BitbucketCloudType
cred.Spec.AvatarURL = bitbucketUser.Links.Avatar.Href
cred.Spec.HTMLURL = bitbucketUser.Links.HTML.Href
cred.Spec.LoginName = bitbucketUser.UserName
cred.Spec.GitLoginName = cloneUserName
cred.Spec.DisplayName = bitbucketUser.DisplayName
return cred
}
func (c *client) getUser(accessToken string) (*User, error) {
url := apiEndpoint + "/user"
b, err := getFromBitbucket(url, accessToken)
if err != nil {
return nil, err
}
user := &User{}
if err := json.Unmarshal(b, user); err != nil {
return nil, err
}
return user, nil
}
func convertRepos(repos []Repository) []v3.SourceCodeRepository {
result := []v3.SourceCodeRepository{}
for _, repo := range repos {
if repo.Scm != "git" {
//skip mercurial repos
continue
}
r := v3.SourceCodeRepository{}
for _, link := range repo.Links.Clone {
if link.Name == "https" {
u, _ := url.Parse(link.Href)
if u != nil {
u.User = nil
r.Spec.URL = u.String()
}
break
}
}
r.Spec.DefaultBranch = repo.MainBranch.Name
r.Spec.Permissions.Admin = true
r.Spec.Permissions.Pull = true
r.Spec.Permissions.Push = true
result = append(result, r)
}
return result
}
func (c *client) Refresh(cred *v3.SourceCodeCredential) (bool, error) {
if cred == nil {
return false, errors.New("cannot refresh empty credentials")
}
config := &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
RedirectURL: c.RedirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
}
source := config.TokenSource(
oauth2.NoContext, &oauth2.Token{RefreshToken: cred.Spec.RefreshToken})
token, err := source.Token()
if err != nil || len(token.AccessToken) == 0 {
return false, err
}
cred.Spec.AccessToken = token.AccessToken
cred.Spec.RefreshToken = token.RefreshToken
cred.Spec.Expiry = token.Expiry.Format(time.RFC3339)
return true, nil
}
func getFromBitbucket(url string, accessToken string) ([]byte, error) {
return doRequestToBitbucket(http.MethodGet, url, accessToken, nil, nil)
}
func doRequestToBitbucket(method string, url string, accessToken string, header map[string]string, body io.Reader) ([]byte, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
client := &http.Client{
Timeout: 15 * time.Second,
}
q := req.URL.Query()
//set to max 100 per page to reduce query time
if method == http.MethodGet {
q.Set("pagelen", maxPerPage)
}
if accessToken != "" {
q.Set("access_token", accessToken)
}
req.URL.RawQuery = q.Encode()
req.Header.Add("Cache-control", "no-cache")
for k, v := range header {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Check the status code
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
var body bytes.Buffer
io.Copy(&body, resp.Body)
return nil, httperror.NewAPIErrorLong(resp.StatusCode, "", body.String())
}
r, err := ioutil.ReadAll(resp.Body)
return r, err
}
func getUserRepoFromURL(repoURL string) (string, string, error) {
reg := regexp.MustCompile(".*/([^/]*?)/([^/]*?).git")
match := reg.FindStringSubmatch(repoURL)
if len(match) != 3 {
return "", "", fmt.Errorf("error getting user/repo from gitrepoUrl:%v", repoURL)
}
return match[1], match[2], nil
}