forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.go
494 lines (443 loc) · 13.1 KB
/
pipeline.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package pipeline
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/pkg/errors"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/rancher/pkg/pipeline/providers"
"github.com/rancher/rancher/pkg/pipeline/remote"
"github.com/rancher/rancher/pkg/pipeline/remote/model"
"github.com/rancher/rancher/pkg/pipeline/utils"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/project.cattle.io/v3"
"github.com/rancher/types/client/project/v3"
"gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/labels"
)
const (
actionRun = "run"
actionPushConfig = "pushconfig"
linkConfigs = "configs"
linkYaml = "yaml"
linkBranches = "branches"
queryBranch = "branch"
queryConfigs = "configs"
)
type Handler struct {
PipelineLister v3.PipelineLister
PipelineExecutions v3.PipelineExecutionInterface
SourceCodeCredentialLister v3.SourceCodeCredentialLister
}
func Formatter(apiContext *types.APIContext, resource *types.RawResource) {
resource.AddAction(apiContext, actionRun)
resource.AddAction(apiContext, actionPushConfig)
resource.Links[linkConfigs] = apiContext.URLBuilder.Link(linkConfigs, resource)
resource.Links[linkYaml] = apiContext.URLBuilder.Link(linkYaml, resource)
resource.Links[linkBranches] = apiContext.URLBuilder.Link(linkBranches, resource)
}
func (h *Handler) LinkHandler(apiContext *types.APIContext, next types.RequestHandler) error {
if apiContext.Link == linkYaml {
if apiContext.Method == http.MethodPut {
return h.updatePipelineConfigYaml(apiContext)
}
return h.getPipelineConfigYAML(apiContext)
} else if apiContext.Link == linkConfigs {
return h.getPipelineConfigJSON(apiContext)
} else if apiContext.Link == linkBranches {
return h.getValidBranches(apiContext)
}
return httperror.NewAPIError(httperror.NotFound, "Link not found")
}
func (h *Handler) ActionHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
switch actionName {
case actionRun:
return h.run(apiContext)
case actionPushConfig:
return h.pushConfig(apiContext)
}
return httperror.NewAPIError(httperror.InvalidAction, "unsupported action")
}
func (h *Handler) run(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
pipeline, err := h.PipelineLister.Get(ns, name)
if err != nil {
return err
}
runPipelineInput := v3.RunPipelineInput{}
requestBytes, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return err
}
if string(requestBytes) != "" {
if err := json.Unmarshal(requestBytes, &runPipelineInput); err != nil {
return err
}
}
branch := runPipelineInput.Branch
if branch == "" {
return httperror.NewAPIError(httperror.InvalidBodyContent, "Error branch is not specified for the pipeline to run")
}
userName := apiContext.Request.Header.Get("Impersonate-User")
pipelineConfig, err := providers.GetPipelineConfigByBranch(h.SourceCodeCredentialLister, pipeline, branch)
if err != nil {
return err
}
if pipelineConfig == nil {
return fmt.Errorf("find no pipeline config to run in the branch")
}
info, err := h.getBuildInfoByBranch(pipeline, branch)
if err != nil {
return err
}
info.TriggerType = utils.TriggerTypeUser
info.TriggerUserName = userName
execution, err := utils.GenerateExecution(h.PipelineExecutions, pipeline, pipelineConfig, info)
if err != nil {
return err
}
if execution == nil {
return errors.New("condition is not match, no build is triggered")
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, client.PipelineExecutionType, ref.Ref(execution), &data); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return err
}
func (h *Handler) pushConfig(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
pipeline, err := h.PipelineLister.Get(ns, name)
if err != nil {
return err
}
pushConfigInput := v3.PushPipelineConfigInput{}
requestBytes, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return err
}
if string(requestBytes) != "" {
if err := json.Unmarshal(requestBytes, &pushConfigInput); err != nil {
return err
}
}
//use current user's auth to do the push
userName := apiContext.Request.Header.Get("Impersonate-User")
creds, err := h.SourceCodeCredentialLister.List(userName, labels.Everything())
if err != nil {
return err
}
accessToken := ""
sourceCodeType := model.GithubType
for _, cred := range creds {
if cred.Spec.ProjectName == pipeline.Spec.ProjectName && !cred.Status.Logout {
accessToken = cred.Spec.AccessToken
sourceCodeType = cred.Spec.SourceCodeType
}
}
_, projID := ref.Parse(pipeline.Spec.ProjectName)
scpConfig, err := providers.GetSourceCodeProviderConfig(sourceCodeType, projID)
if err != nil {
return err
}
remote, err := remote.New(scpConfig)
if err != nil {
return err
}
for branch, config := range pushConfigInput.Configs {
content, err := utils.PipelineConfigToYaml(&config)
if err != nil {
return err
}
if err := remote.SetPipelineFileInRepo(pipeline.Spec.RepositoryURL, branch, accessToken, content); err != nil {
if apierr, ok := err.(*httperror.APIError); ok && apierr.Code.Status == http.StatusNotFound {
//github returns 404 for unauth request to prevent leakage of private repos
return httperror.NewAPIError(httperror.Unauthorized, "current git account is unauthorized for the action")
}
return err
}
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &data); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (h *Handler) getBuildInfoByBranch(pipeline *v3.Pipeline, branch string) (*model.BuildInfo, error) {
credentialName := pipeline.Spec.SourceCodeCredentialName
repoURL := pipeline.Spec.RepositoryURL
accessToken := ""
sourceCodeType := model.GithubType
var scpConfig interface{}
if credentialName != "" {
ns, name := ref.Parse(credentialName)
credential, err := h.SourceCodeCredentialLister.Get(ns, name)
if err != nil {
return nil, err
}
sourceCodeType = credential.Spec.SourceCodeType
accessToken = credential.Spec.AccessToken
_, projID := ref.Parse(pipeline.Spec.ProjectName)
scpConfig, err = providers.GetSourceCodeProviderConfig(sourceCodeType, projID)
if err != nil {
return nil, err
}
}
remote, err := remote.New(scpConfig)
if err != nil {
return nil, err
}
info, err := remote.GetHeadInfo(repoURL, branch, accessToken)
if err != nil {
return nil, err
}
return info, nil
}
func (h *Handler) getValidBranches(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
pipeline, err := h.PipelineLister.Get(ns, name)
if err != nil {
return err
}
accessKey := ""
sourceCodeType := model.GithubType
var scpConfig interface{}
if pipeline.Spec.SourceCodeCredentialName != "" {
ns, name = ref.Parse(pipeline.Spec.SourceCodeCredentialName)
cred, err := h.SourceCodeCredentialLister.Get(ns, name)
if err != nil {
return err
}
accessKey = cred.Spec.AccessToken
sourceCodeType = cred.Spec.SourceCodeType
_, projID := ref.Parse(pipeline.Spec.ProjectName)
scpConfig, err = providers.GetSourceCodeProviderConfig(sourceCodeType, projID)
if err != nil {
return err
}
}
remote, err := remote.New(scpConfig)
if err != nil {
return err
}
validBranches := map[string]bool{}
branches, err := remote.GetBranches(pipeline.Spec.RepositoryURL, accessKey)
if err != nil {
return err
}
for _, b := range branches {
content, err := remote.GetPipelineFileInRepo(pipeline.Spec.RepositoryURL, b, accessKey)
if err != nil {
return err
}
if content != nil {
validBranches[b] = true
}
}
result := []string{}
for b := range validBranches {
result = append(result, b)
}
bytes, err := json.Marshal(result)
if err != nil {
return err
}
apiContext.Response.Write(bytes)
return nil
}
func (h *Handler) getPipelineConfigJSON(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
pipeline, err := h.PipelineLister.Get(ns, name)
if err != nil {
return err
}
branch := apiContext.Request.URL.Query().Get(queryBranch)
m, err := h.getPipelineConfigs(pipeline, branch)
if err != nil {
return err
}
bytes, err := json.Marshal(m)
if err != nil {
return err
}
apiContext.Response.Write(bytes)
return nil
}
func (h *Handler) getPipelineConfigYAML(apiContext *types.APIContext) error {
yamlMap := map[string]interface{}{}
m := map[string]*v3.PipelineConfig{}
branch := apiContext.Request.URL.Query().Get(queryBranch)
configs := apiContext.Request.URL.Query().Get(queryConfigs)
if configs != "" {
err := json.Unmarshal([]byte(configs), &m)
if err != nil {
return err
}
for b, config := range m {
if config == nil {
yamlMap[b] = nil
continue
}
content, err := utils.PipelineConfigToYaml(config)
if err != nil {
return err
}
yamlMap[b] = string(content)
}
} else {
ns, name := ref.Parse(apiContext.ID)
pipeline, err := h.PipelineLister.Get(ns, name)
if err != nil {
return err
}
m, err = h.getPipelineConfigs(pipeline, branch)
if err != nil {
return err
}
}
if branch != "" {
config := m[branch]
if config == nil {
return nil
}
content, err := utils.PipelineConfigToYaml(config)
if err != nil {
return err
}
apiContext.Response.Write(content)
return nil
}
for b, config := range m {
if config == nil {
yamlMap[b] = nil
continue
}
content, err := utils.PipelineConfigToYaml(config)
if err != nil {
return err
}
yamlMap[b] = string(content)
}
bytes, err := json.Marshal(yamlMap)
if err != nil {
return err
}
apiContext.Response.Write(bytes)
return nil
}
func (h *Handler) updatePipelineConfigYaml(apiContext *types.APIContext) error {
branch := apiContext.Request.URL.Query().Get(queryBranch)
if branch == "" {
return httperror.NewAPIError(httperror.InvalidOption, "Branch is not specified")
}
ns, name := ref.Parse(apiContext.ID)
pipeline, err := h.PipelineLister.Get(ns, name)
if err != nil {
return err
}
content, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return err
}
//check yaml
config := &v3.PipelineConfig{}
if err := yaml.Unmarshal(content, config); err != nil {
return err
}
//use current user's auth to do the push
userName := apiContext.Request.Header.Get("Impersonate-User")
creds, err := h.SourceCodeCredentialLister.List(userName, labels.Everything())
if err != nil {
return err
}
accessToken := ""
sourceCodeType := model.GithubType
for _, cred := range creds {
if cred.Spec.ProjectName == pipeline.Spec.ProjectName && !cred.Status.Logout {
accessToken = cred.Spec.AccessToken
sourceCodeType = cred.Spec.SourceCodeType
}
}
_, projID := ref.Parse(pipeline.Spec.ProjectName)
scpConfig, err := providers.GetSourceCodeProviderConfig(sourceCodeType, projID)
if err != nil {
return err
}
remote, err := remote.New(scpConfig)
if err != nil {
return err
}
if err := remote.SetPipelineFileInRepo(pipeline.Spec.RepositoryURL, branch, accessToken, content); err != nil {
if apierr, ok := err.(*httperror.APIError); ok && apierr.Code.Status == http.StatusNotFound {
//github returns 404 for unauth request to prevent leakage of private repos
return httperror.NewAPIError(httperror.Unauthorized, "current git account is unauthorized for the action")
}
return err
}
return nil
}
func (h *Handler) getPipelineConfigs(pipeline *v3.Pipeline, branch string) (map[string]*v3.PipelineConfig, error) {
accessToken := ""
sourceCodeType := model.GithubType
var scpConfig interface{}
if pipeline.Spec.SourceCodeCredentialName != "" {
ns, name := ref.Parse(pipeline.Spec.SourceCodeCredentialName)
cred, err := h.SourceCodeCredentialLister.Get(ns, name)
if err != nil {
return nil, err
}
sourceCodeType = cred.Spec.SourceCodeType
accessToken = cred.Spec.AccessToken
_, projID := ref.Parse(pipeline.Spec.ProjectName)
scpConfig, err = providers.GetSourceCodeProviderConfig(sourceCodeType, projID)
if err != nil {
return nil, err
}
}
remote, err := remote.New(scpConfig)
if err != nil {
return nil, err
}
m := map[string]*v3.PipelineConfig{}
if branch != "" {
content, err := remote.GetPipelineFileInRepo(pipeline.Spec.RepositoryURL, branch, accessToken)
if err != nil {
return nil, err
}
if content != nil {
spec, err := utils.PipelineConfigFromYaml(content)
if err != nil {
return nil, errors.Wrapf(err, "Error fetching pipeline config in Branch '%s'", branch)
}
m[branch] = spec
} else {
m[branch] = nil
}
} else {
branches, err := remote.GetBranches(pipeline.Spec.RepositoryURL, accessToken)
if err != nil {
return nil, err
}
for _, b := range branches {
content, err := remote.GetPipelineFileInRepo(pipeline.Spec.RepositoryURL, b, accessToken)
if err != nil {
return nil, err
}
if content != nil {
spec, err := utils.PipelineConfigFromYaml(content)
if err != nil {
return nil, errors.Wrapf(err, "Error fetching pipeline config in Branch '%s'", b)
}
m[b] = spec
} else {
m[b] = nil
}
}
}
return m, nil
}