forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
389 lines (334 loc) · 9.82 KB
/
github.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
package github
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/google/go-github/github"
"github.com/pkg/errors"
"github.com/rancher/rancher/pkg/catalog/git"
"github.com/rancher/rancher/pkg/controllers/user/pipeline/remote/model"
"github.com/rancher/rancher/pkg/controllers/user/pipeline/utils"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
"github.com/tomnomnom/linkheader"
"golang.org/x/oauth2"
"io"
"io/ioutil"
"net/http"
"strings"
)
const (
defaultGithubAPI = "https://api.github.com"
maxPerPage = "100"
gheAPI = "/api/v3"
)
type client struct {
Scheme string
Host string
ClientID string
ClientSecret string
API string
}
func New(pipeline v3.ClusterPipeline) (model.Remote, error) {
if pipeline.Spec.GithubConfig == nil {
return nil, errors.New("github is not configured")
}
remote := &client{
ClientID: pipeline.Spec.GithubConfig.ClientID,
ClientSecret: pipeline.Spec.GithubConfig.ClientSecret,
}
if pipeline.Spec.GithubConfig.Host != "" && pipeline.Spec.GithubConfig.Host != "github.com" {
remote.Host = pipeline.Spec.GithubConfig.Host
if pipeline.Spec.GithubConfig.TLS {
remote.Scheme = "https://"
} else {
remote.Scheme = "http://"
}
remote.API = remote.Scheme + remote.Host + gheAPI
} else {
remote.Scheme = "https://"
remote.Host = "github.com"
remote.API = defaultGithubAPI
}
return remote, nil
}
func (c *client) Type() string {
return "github"
}
func (c *client) CanLogin() bool {
return true
}
func (c *client) CanRepos() bool {
return true
}
func (c *client) CanHook() bool {
return true
}
func (c *client) Login(redirectURL string, code string) (*v3.SourceCodeCredential, error) {
githubOauthConfig := &oauth2.Config{
RedirectURL: redirectURL,
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
Scopes: []string{"repo",
"admin:repo_hook"},
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("%s%s/login/oauth/authorize", c.Scheme, c.Host),
TokenURL: fmt.Sprintf("%s%s/login/oauth/access_token", c.Scheme, c.Host),
},
}
token, err := githubOauthConfig.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")
}
return c.GetAccount(token.AccessToken)
}
func (c *client) CreateHook(pipeline *v3.Pipeline, accessToken string) (string, error) {
if err := utils.ValidPipelineSpec(pipeline.Spec); err != nil {
return "", err
}
sourceCodeConfig := pipeline.Spec.Stages[0].Steps[0].SourceCodeConfig
user, repo, err := getUserRepoFromURL(sourceCodeConfig.URL)
if err != nil {
return "", err
}
events := []string{"push", "pull_request"}
hookURL := fmt.Sprintf("%s?pipelineId=%s:%s", utils.CIEndpoint, pipeline.Namespace, pipeline.Name)
id, err := c.createGithubWebhook(user, repo, accessToken, hookURL, pipeline.Status.Token, events)
if err != nil {
return "", err
}
return id, nil
}
func (c *client) DeleteHook(pipeline *v3.Pipeline, accessToken string) error {
if err := utils.ValidPipelineSpec(pipeline.Spec); err != nil {
return err
}
sourceCodeConfig := pipeline.Spec.Stages[0].Steps[0].SourceCodeConfig
user, repo, err := getUserRepoFromURL(sourceCodeConfig.URL)
if err != nil {
return err
}
return c.deleteGithubWebhook(user, repo, accessToken, pipeline.Status.WebHookID)
}
func (c *client) ParseHook(r *http.Request) {
}
func (c *client) GetAccount(accessToken string) (*v3.SourceCodeCredential, error) {
account, err := c.getGithubUser(accessToken)
if err != nil {
return nil, err
}
remoteAccount := convertAccount(account)
remoteAccount.Spec.AccessToken = accessToken
return remoteAccount, nil
}
func (c *client) Repos(account *v3.SourceCodeCredential) ([]v3.SourceCodeRepository, error) {
if account == nil {
return nil, fmt.Errorf("empty account")
}
accessToken := account.Spec.AccessToken
return c.getGithubRepos(accessToken)
}
func (c *client) getGithubUser(githubAccessToken string) (*github.User, error) {
url := c.API + "/user"
resp, err := getFromGithub(githubAccessToken, url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
githubAcct := &github.User{}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, githubAcct); err != nil {
return nil, err
}
return githubAcct, nil
}
func convertAccount(gitaccount *github.User) *v3.SourceCodeCredential {
if gitaccount == nil {
return nil
}
account := &v3.SourceCodeCredential{}
account.Spec.SourceCodeType = "github"
account.Spec.AvatarURL = gitaccount.GetAvatarURL()
account.Spec.HTMLURL = gitaccount.GetHTMLURL()
account.Spec.LoginName = gitaccount.GetLogin()
account.Spec.DisplayName = gitaccount.GetName()
return account
}
func (c *client) getGithubRepos(githubAccessToken string) ([]v3.SourceCodeRepository, error) {
url := c.API + "/user/repos"
var repos []github.Repository
responses, err := paginateGithub(githubAccessToken, url)
if err != nil {
return nil, err
}
for _, response := range responses {
defer response.Body.Close()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var reposObj []github.Repository
if err := json.Unmarshal(b, &reposObj); err != nil {
return nil, err
}
repos = append(repos, reposObj...)
}
return convertRepos(repos), nil
}
func (c *client) getFileContent(filename string, owner string, repo string, ref string, githubAccessToken string) (*github.RepositoryContent, error) {
url := fmt.Sprintf("%s/repos/%s/%s/contents/%s", c.API, owner, repo, filename)
if ref != "" {
url = url + "?ref=" + ref
}
resp, err := getFromGithub(githubAccessToken, url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
fileContent := &github.RepositoryContent{}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, fileContent); err != nil {
return nil, err
}
return fileContent, nil
}
func (c *client) GetPipelineFileInRepo(repoURL string, ref string, accessToken string) ([]byte, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return nil, err
}
content, err := c.getFileContent(".pipeline.yaml", owner, repo, ref, accessToken)
if err != nil {
//look for both suffix
content, err = c.getFileContent(".pipeline.yml", owner, repo, ref, accessToken)
}
if err != nil {
logrus.Debugf("error GetPipelineFileInRepo - %v", err)
return nil, nil
}
if content.Content != nil {
b, err := base64.StdEncoding.DecodeString(*content.Content)
if err != nil {
return nil, err
}
return b, nil
}
return nil, nil
}
func (c *client) GetDefaultBranch(repoURL string, accessToken string) (string, error) {
owner, repo, err := getUserRepoFromURL(repoURL)
if err != nil {
return "", err
}
url := fmt.Sprintf("%s/repos/%s/%s", c.API, owner, repo)
resp, err := getFromGithub(accessToken, url)
if err != nil {
return "", err
}
defer resp.Body.Close()
repository := &github.Repository{}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if err := json.Unmarshal(b, repository); err != nil {
return "", err
}
if repository.DefaultBranch != nil {
return *repository.DefaultBranch, nil
}
return "", nil
}
func (c *client) GetHeadCommit(repoURL string, branch string, credential *v3.SourceCodeCredential) (string, error) {
if credential != nil {
userName := credential.Spec.LoginName
token := credential.Spec.AccessToken
repoURL = strings.Replace(repoURL, "://", "://"+userName+":"+token+"@", 1)
}
return git.RemoteBranchHeadCommit(repoURL, branch)
}
func convertRepos(repos []github.Repository) []v3.SourceCodeRepository {
result := []v3.SourceCodeRepository{}
for _, repo := range repos {
r := v3.SourceCodeRepository{}
r.Spec.URL = repo.GetCloneURL()
r.Spec.Language = repo.GetLanguage()
r.Spec.DefaultBranch = repo.GetDefaultBranch()
permissions := repo.GetPermissions()
r.Spec.Permissions.Pull = permissions["pull"]
r.Spec.Permissions.Push = permissions["push"]
r.Spec.Permissions.Admin = permissions["admin"]
result = append(result, r)
}
return result
}
func paginateGithub(githubAccessToken string, url string) ([]*http.Response, error) {
var responses []*http.Response
response, err := getFromGithub(githubAccessToken, url)
if err != nil {
return responses, err
}
responses = append(responses, response)
nextURL := nextGithubPage(response)
for nextURL != "" {
response, err = getFromGithub(githubAccessToken, nextURL)
if err != nil {
return responses, err
}
responses = append(responses, response)
nextURL = nextGithubPage(response)
}
return responses, nil
}
func getFromGithub(githubAccessToken string, url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
client := &http.Client{}
//set to max 100 per page to reduce query time
q := req.URL.Query()
q.Set("per_page", maxPerPage)
req.URL.RawQuery = q.Encode()
if githubAccessToken != "" {
req.Header.Add("Authorization", "token "+githubAccessToken)
}
req.Header.Add("Accept", "application/json")
req.Header.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36)")
resp, err := client.Do(req)
if err != nil {
return resp, err
}
// Check the status code
switch resp.StatusCode {
case 200:
case 201:
default:
var body bytes.Buffer
io.Copy(&body, resp.Body)
return resp, fmt.Errorf("Request failed, got status code: %d. Response: %s",
resp.StatusCode, body.Bytes())
}
return resp, nil
}
func nextGithubPage(response *http.Response) string {
header := response.Header.Get("link")
if header != "" {
links := linkheader.Parse(header)
for _, link := range links {
if link.Rel == "next" {
return link.URL
}
}
}
return ""
}