/
CiService.go
364 lines (333 loc) · 13.8 KB
/
CiService.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
/*
* Copyright (c) 2020 Devtron Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pipeline
import (
"fmt"
"github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
"github.com/devtron-labs/devtron/client/events"
"github.com/devtron-labs/devtron/internal/middleware"
"github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig"
"github.com/devtron-labs/devtron/internal/util"
"github.com/devtron-labs/devtron/pkg/bean"
util2 "github.com/devtron-labs/devtron/util/event"
"go.uber.org/zap"
"path/filepath"
"strconv"
"time"
)
type CiService interface {
TriggerCiPipeline(trigger Trigger) (int, error)
GetCiMaterials(pipelineId int, ciMaterials []*pipelineConfig.CiPipelineMaterial) ([]*pipelineConfig.CiPipelineMaterial, error)
}
type CiServiceImpl struct {
Logger *zap.SugaredLogger
workflowService WorkflowService
ciPipelineMaterialRepository pipelineConfig.CiPipelineMaterialRepository
ciWorkflowRepository pipelineConfig.CiWorkflowRepository
ciConfig *CiConfig
eventClient client.EventClient
eventFactory client.EventFactory
mergeUtil *util.MergeUtil
ciPipelineRepository pipelineConfig.CiPipelineRepository
}
func NewCiServiceImpl(Logger *zap.SugaredLogger, workflowService WorkflowService, ciPipelineMaterialRepository pipelineConfig.CiPipelineMaterialRepository,
ciWorkflowRepository pipelineConfig.CiWorkflowRepository, ciConfig *CiConfig, eventClient client.EventClient, eventFactory client.EventFactory, mergeUtil *util.MergeUtil, ciPipelineRepository pipelineConfig.CiPipelineRepository) *CiServiceImpl {
return &CiServiceImpl{
Logger: Logger,
workflowService: workflowService,
ciPipelineMaterialRepository: ciPipelineMaterialRepository,
ciWorkflowRepository: ciWorkflowRepository,
ciConfig: ciConfig,
eventClient: eventClient,
eventFactory: eventFactory,
mergeUtil: mergeUtil,
ciPipelineRepository: ciPipelineRepository,
}
}
const WorkflowStarting = "Starting"
const WorkflowAborted = "Aborted"
const WorkflowFailed = "Failed"
func (impl *CiServiceImpl) GetCiMaterials(pipelineId int, ciMaterials []*pipelineConfig.CiPipelineMaterial) ([]*pipelineConfig.CiPipelineMaterial, error) {
if !(ciMaterials == nil || len(ciMaterials) == 0) {
return ciMaterials, nil
} else {
ciMaterials, err := impl.ciPipelineMaterialRepository.GetByPipelineId(pipelineId)
if err != nil {
impl.Logger.Errorw("err", "err", err)
return nil, err
}
impl.Logger.Debug("ciMaterials for pipeline trigger ", ciMaterials)
return ciMaterials, nil
}
}
func (impl *CiServiceImpl) TriggerCiPipeline(trigger Trigger) (int, error) {
impl.Logger.Debug("ci pipeline manual trigger")
ciMaterials, err := impl.GetCiMaterials(trigger.PipelineId, trigger.CiMaterials)
if err != nil {
return 0, err
}
ciPipelineScripts, err := impl.ciPipelineRepository.FindCiScriptsByCiPipelineId(trigger.PipelineId)
if err != nil && !util.IsErrNoRows(err) {
return 0, err
}
var pipeline *pipelineConfig.CiPipeline
for _, m := range ciMaterials {
pipeline = m.CiPipeline
break
}
ciWorkflowConfig, err := impl.ciWorkflowRepository.FindConfigByPipelineId(trigger.PipelineId)
if err != nil && !util.IsErrNoRows(err) {
impl.Logger.Errorw("could not fetch ci config", "pipeline", trigger.PipelineId)
return 0, err
}
if ciWorkflowConfig.Namespace == "" {
ciWorkflowConfig.Namespace = impl.ciConfig.DefaultNamespace
}
savedCiWf, err := impl.saveNewWorkflow(pipeline, ciWorkflowConfig, trigger.CommitHashes, trigger.TriggeredBy)
if err != nil {
impl.Logger.Errorw("could not save new workflow", "err", err)
return 0, err
}
workflowRequest, err := impl.buildWfRequestForCiPipeline(pipeline, trigger, ciMaterials, savedCiWf, ciWorkflowConfig, ciPipelineScripts)
if err != nil {
impl.Logger.Errorw("make workflow req", "err", err)
return 0, err
}
createdWf, err := impl.executeCiPipeline(workflowRequest)
if err != nil {
impl.Logger.Errorw("workflow error", "err", err)
return 0, err
}
impl.Logger.Debugw("ci triggered", "wf name ", createdWf.Name, " pipeline ", trigger.PipelineId)
middleware.CiTriggerCounter.WithLabelValues(strconv.Itoa(pipeline.AppId), strconv.Itoa(trigger.PipelineId)).Inc()
go impl.WriteCITriggerEvent(trigger, pipeline, workflowRequest)
return savedCiWf.Id, err
}
func (impl *CiServiceImpl) WriteCITriggerEvent(trigger Trigger, pipeline *pipelineConfig.CiPipeline, workflowRequest *WorkflowRequest) {
event := impl.eventFactory.Build(util2.Trigger, &pipeline.Id, pipeline.AppId, nil, util2.CI)
material := &client.MaterialTriggerInfo{}
gitT := make(map[int]pipelineConfig.GitCommit)
for k, v := range trigger.CommitHashes {
gitT[k] = pipelineConfig.GitCommit{
Commit: v.Commit,
Author: v.Author,
Changes: v.Changes,
Message: v.Message,
Date: v.Date,
}
}
material.GitTriggers = gitT
event.UserId = int(trigger.TriggeredBy)
event.CiWorkflowRunnerId = workflowRequest.WorkflowId
event = impl.eventFactory.BuildExtraCIData(event, material, workflowRequest.CiImage)
_, evtErr := impl.eventClient.WriteEvent(event)
if evtErr != nil {
impl.Logger.Errorw("error in writing event", "err", evtErr)
}
}
// TODO: Send all trigger data
func (impl *CiServiceImpl) BuildPayload(trigger Trigger, pipeline *pipelineConfig.CiPipeline, workflowRequest *WorkflowRequest) *client.Payload {
payload := &client.Payload{}
payload.AppName = pipeline.App.AppName
payload.PipelineName = pipeline.Name
return payload
}
func (impl *CiServiceImpl) saveNewWorkflow(pipeline *pipelineConfig.CiPipeline, wfConfig *pipelineConfig.CiWorkflowConfig,
commitHashes map[int]bean.GitCommit, userId int32) (wf *pipelineConfig.CiWorkflow, error error) {
gitTriggers := make(map[int]pipelineConfig.GitCommit)
for k, v := range commitHashes {
gitTriggers[k] = pipelineConfig.GitCommit{
Commit: v.Commit,
Author: v.Author,
Date: v.Date,
Message: v.Message,
Changes: v.Changes,
}
}
ciWorkflow := &pipelineConfig.CiWorkflow{
Name: pipeline.Name + "-" + strconv.Itoa(pipeline.Id),
Status: WorkflowStarting,
Message: "",
StartedOn: time.Now(),
CiPipelineId: pipeline.Id,
Namespace: wfConfig.Namespace,
GitTriggers: gitTriggers,
LogLocation: "",
TriggeredBy: userId,
}
err := impl.ciWorkflowRepository.SaveWorkFlow(ciWorkflow)
if err != nil {
impl.Logger.Errorw("saving workflow error", "err", err)
return &pipelineConfig.CiWorkflow{}, err
}
impl.Logger.Debugw("workflow saved ", "id", ciWorkflow.Id)
return ciWorkflow, nil
}
func (impl *CiServiceImpl) executeCiPipeline(workflowRequest *WorkflowRequest) (*v1alpha1.Workflow, error) {
createdWorkFlow, err := impl.workflowService.SubmitWorkflow(workflowRequest)
if err != nil {
impl.Logger.Errorw("workflow error", "err", err)
return nil, err
}
return createdWorkFlow, nil
}
func (impl *CiServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineConfig.CiPipeline, trigger Trigger,
ciMaterials []*pipelineConfig.CiPipelineMaterial, savedWf *pipelineConfig.CiWorkflow,
ciWorkflowConfig *pipelineConfig.CiWorkflowConfig, ciPipelineScripts []*pipelineConfig.CiPipelineScript) (*WorkflowRequest, error) {
var ciProjectDetails []CiProjectDetails
commitHashes := trigger.CommitHashes
for _, ciMaterial := range ciMaterials {
ciProjectDetail := CiProjectDetails{
GitRepository: ciMaterial.GitMaterial.Url,
MaterialName: ciMaterial.GitMaterial.Name,
CheckoutPath: ciMaterial.GitMaterial.CheckoutPath,
CommitHash: commitHashes[ciMaterial.Id].Commit,
Author: commitHashes[ciMaterial.Id].Author,
SourceType: ciMaterial.Type,
SourceValue: ciMaterial.Value,
GitTag: ciMaterial.GitTag,
Message: commitHashes[ciMaterial.Id].Message,
Type: string(ciMaterial.Type),
CommitTime: commitHashes[ciMaterial.Id].Date,
GitOptions: GitOptions{
UserName: ciMaterial.GitMaterial.GitProvider.UserName,
Password: ciMaterial.GitMaterial.GitProvider.Password,
SSHKey: ciMaterial.GitMaterial.GitProvider.SshKey,
AccessToken: ciMaterial.GitMaterial.GitProvider.AccessToken,
AuthMode: ciMaterial.GitMaterial.GitProvider.AuthMode,
},
}
ciProjectDetails = append(ciProjectDetails, ciProjectDetail)
}
var beforeDockerBuildScripts []*bean.CiScript
var afterDockerBuildScripts []*bean.CiScript
for _, ciPipelineScript := range ciPipelineScripts {
ciTask := &bean.CiScript{
Id: ciPipelineScript.Id,
Index: ciPipelineScript.Index,
Name: ciPipelineScript.Name,
Script: ciPipelineScript.Script,
OutputLocation: ciPipelineScript.OutputLocation,
}
if ciPipelineScript.Stage == BEFORE_DOCKER_BUILD {
beforeDockerBuildScripts = append(beforeDockerBuildScripts, ciTask)
} else if ciPipelineScript.Stage == AFTER_DOCKER_BUILD {
afterDockerBuildScripts = append(afterDockerBuildScripts, ciTask)
}
}
dockerImageTag := impl.buildImageTag(commitHashes, pipeline.Id, savedWf.Id)
if ciWorkflowConfig.CiCacheBucket == "" {
ciWorkflowConfig.CiCacheBucket = impl.ciConfig.DefaultCacheBucket
}
if ciWorkflowConfig.LogsBucket == "" {
ciWorkflowConfig.LogsBucket = impl.ciConfig.DefaultBuildLogsBucket
}
ciArtifactLocationFormat := ciWorkflowConfig.CiArtifactLocationFormat
if ciArtifactLocationFormat == "" {
ciArtifactLocationFormat = impl.ciConfig.CiArtifactLocationFormat
}
ciArtifactLocation := fmt.Sprintf("s3://%s/"+impl.ciConfig.DefaultArtifactKeyPrefix+"/"+ciArtifactLocationFormat, ciWorkflowConfig.LogsBucket, savedWf.Id, savedWf.Id)
if ciWorkflowConfig.CiCacheRegion == "" {
ciWorkflowConfig.CiCacheRegion = impl.ciConfig.DefaultCacheBucketRegion
}
if ciWorkflowConfig.CiImage == "" {
ciWorkflowConfig.CiImage = impl.ciConfig.DefaultImage
}
if ciWorkflowConfig.CiTimeout == 0 {
ciWorkflowConfig.CiTimeout = impl.ciConfig.DefaultTimeout
}
args := pipeline.CiTemplate.Args
ciLevelArgs := pipeline.DockerArgs
if ciLevelArgs == "" {
ciLevelArgs = "{}"
}
merged, err := impl.mergeUtil.JsonPatch([]byte(args), []byte(ciLevelArgs))
if err != nil {
impl.Logger.Errorw("err", "err", err)
return nil, err
}
checkoutPath := pipeline.CiTemplate.GitMaterial.CheckoutPath
if len(checkoutPath) == 0 {
checkoutPath = "./"
}
dockerfilePath := filepath.Join(pipeline.CiTemplate.GitMaterial.CheckoutPath, pipeline.CiTemplate.DockerfilePath)
workflowRequest := &WorkflowRequest{
WorkflowNamePrefix: strconv.Itoa(savedWf.Id) + "-" + savedWf.Name,
PipelineName: pipeline.Name,
PipelineId: pipeline.Id,
DockerRegistryType: string(pipeline.CiTemplate.DockerRegistry.RegistryType),
DockerImageTag: dockerImageTag,
DockerRegistryURL: pipeline.CiTemplate.DockerRegistry.RegistryURL,
DockerRepository: pipeline.CiTemplate.DockerRepository,
DockerBuildArgs: string(merged),
DockerFileLocation: dockerfilePath,
DockerUsername: pipeline.CiTemplate.DockerRegistry.Username,
DockerPassword: pipeline.CiTemplate.DockerRegistry.Password,
AwsRegion: pipeline.CiTemplate.DockerRegistry.AWSRegion,
AccessKey: pipeline.CiTemplate.DockerRegistry.AWSAccessKeyId,
SecretKey: pipeline.CiTemplate.DockerRegistry.AWSSecretAccessKey,
CiCacheFileName: pipeline.Name + "-" + strconv.Itoa(pipeline.Id) + ".tar.gz",
CiProjectDetails: ciProjectDetails,
Namespace: ciWorkflowConfig.Namespace,
CiImage: ciWorkflowConfig.CiImage,
ActiveDeadlineSeconds: ciWorkflowConfig.CiTimeout,
WorkflowId: savedWf.Id,
TriggeredBy: savedWf.TriggeredBy,
CacheLimit: impl.ciConfig.CacheLimit,
BeforeDockerBuildScripts: beforeDockerBuildScripts,
AfterDockerBuildScripts: afterDockerBuildScripts,
CiArtifactLocation: ciArtifactLocation,
InvalidateCache: trigger.InvalidateCache,
ScanEnabled: pipeline.ScanEnabled,
CloudProvider: impl.ciConfig.CloudProvider,
}
switch workflowRequest.CloudProvider {
case BLOB_STORAGE_S3:
workflowRequest.CiCacheRegion = ciWorkflowConfig.CiCacheRegion
workflowRequest.CiCacheLocation = ciWorkflowConfig.CiCacheBucket
case BLOB_STORAGE_AZURE:
workflowRequest.AzureBlobConfig = &AzureBlobConfig{
Enabled: impl.ciConfig.CloudProvider == BLOB_STORAGE_AZURE,
AccountName: impl.ciConfig.AzureAccountName,
BlobContainerCiCache: impl.ciConfig.AzureBlobContainerCiCache,
AccountKey: impl.ciConfig.AzureAccountKey,
}
case BLOB_STORAGE_MINIO:
workflowRequest.CiCacheLocation = ciWorkflowConfig.CiCacheBucket
workflowRequest.MinioEndpoint = impl.ciConfig.MinioEndpoint
default:
return nil, fmt.Errorf("cloudprovider %s not supported", workflowRequest.CloudProvider)
}
return workflowRequest, nil
}
func (impl *CiServiceImpl) buildImageTag(commitHashes map[int]bean.GitCommit, id int, wfId int) string {
dockerImageTag := ""
for _, v := range commitHashes {
if v.Commit == "" {
continue
}
if dockerImageTag == "" {
dockerImageTag = v.Commit[:8]
} else {
dockerImageTag = dockerImageTag + "-" + v.Commit[:8]
}
}
if dockerImageTag != "" {
dockerImageTag = dockerImageTag + "-" + strconv.Itoa(id) + "-" + strconv.Itoa(wfId)
}
return dockerImageTag
}