-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathHandlerService.go
More file actions
2068 lines (1908 loc) · 90.5 KB
/
HandlerService.go
File metadata and controls
2068 lines (1908 loc) · 90.5 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package trigger
import (
"bufio"
"context"
"errors"
"fmt"
"github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/caarlos0/env"
"github.com/devtron-labs/common-lib/async"
blob_storage "github.com/devtron-labs/common-lib/blob-storage"
"github.com/devtron-labs/common-lib/utils"
bean4 "github.com/devtron-labs/common-lib/utils/bean"
"github.com/devtron-labs/common-lib/utils/k8s"
commonBean "github.com/devtron-labs/common-lib/workflow"
client "github.com/devtron-labs/devtron/client/events"
"github.com/devtron-labs/devtron/client/gitSensor"
"github.com/devtron-labs/devtron/internal/middleware"
"github.com/devtron-labs/devtron/internal/sql/constants"
repository5 "github.com/devtron-labs/devtron/internal/sql/repository"
appRepository "github.com/devtron-labs/devtron/internal/sql/repository/app"
repository3 "github.com/devtron-labs/devtron/internal/sql/repository/dockerRegistry"
"github.com/devtron-labs/devtron/internal/sql/repository/helper"
"github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig"
"github.com/devtron-labs/devtron/internal/sql/repository/pipelineConfig/bean/workflow/cdWorkflow"
"github.com/devtron-labs/devtron/internal/util"
"github.com/devtron-labs/devtron/pkg/app"
"github.com/devtron-labs/devtron/pkg/attributes"
bean3 "github.com/devtron-labs/devtron/pkg/attributes/bean"
"github.com/devtron-labs/devtron/pkg/auth/user"
bean6 "github.com/devtron-labs/devtron/pkg/auth/user/bean"
"github.com/devtron-labs/devtron/pkg/bean"
"github.com/devtron-labs/devtron/pkg/bean/common"
"github.com/devtron-labs/devtron/pkg/build/pipeline"
buildBean "github.com/devtron-labs/devtron/pkg/build/pipeline/bean"
buildCommonBean "github.com/devtron-labs/devtron/pkg/build/pipeline/bean/common"
"github.com/devtron-labs/devtron/pkg/build/trigger/adaptor"
"github.com/devtron-labs/devtron/pkg/cluster"
adapter2 "github.com/devtron-labs/devtron/pkg/cluster/adapter"
clusterBean "github.com/devtron-labs/devtron/pkg/cluster/bean"
"github.com/devtron-labs/devtron/pkg/cluster/environment"
repository6 "github.com/devtron-labs/devtron/pkg/cluster/environment/repository"
eventProcessorBean "github.com/devtron-labs/devtron/pkg/eventProcessor/bean"
"github.com/devtron-labs/devtron/pkg/executor"
pipeline2 "github.com/devtron-labs/devtron/pkg/pipeline"
"github.com/devtron-labs/devtron/pkg/pipeline/adapter"
pipelineConfigBean "github.com/devtron-labs/devtron/pkg/pipeline/bean"
constants2 "github.com/devtron-labs/devtron/pkg/pipeline/constants"
"github.com/devtron-labs/devtron/pkg/pipeline/executors"
"github.com/devtron-labs/devtron/pkg/pipeline/repository"
"github.com/devtron-labs/devtron/pkg/pipeline/types"
util2 "github.com/devtron-labs/devtron/pkg/pipeline/util"
"github.com/devtron-labs/devtron/pkg/plugin"
bean2 "github.com/devtron-labs/devtron/pkg/plugin/bean"
repository2 "github.com/devtron-labs/devtron/pkg/plugin/repository"
"github.com/devtron-labs/devtron/pkg/resourceQualifiers"
"github.com/devtron-labs/devtron/pkg/variables"
repository4 "github.com/devtron-labs/devtron/pkg/variables/repository"
auditService "github.com/devtron-labs/devtron/pkg/workflow/trigger/audit/service"
"github.com/devtron-labs/devtron/util/sliceUtil"
"github.com/go-pg/pg"
"go.uber.org/zap"
"io/ioutil"
"k8s.io/client-go/rest"
"net/http"
"os"
"path"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
)
type HandlerService interface {
HandlePodDeleted(ciWorkflow *pipelineConfig.CiWorkflow)
CheckAndReTriggerCI(workflowStatus eventProcessorBean.CiCdStatus) error
HandleCIManual(ciTriggerRequest bean.CiTriggerRequest) (int, error)
HandleCIWebhook(gitCiTriggerRequest bean.GitCiTriggerRequest) (int, error)
StartCiWorkflowAndPrepareWfRequest(trigger *types.CiTriggerRequest) (map[string]string, *pipelineConfig.CiWorkflow, *types.WorkflowRequest, error)
CancelBuild(workflowId int, forceAbort bool) (int, error)
GetRunningWorkflowLogs(workflowId int, followLogs bool) (*bufio.Reader, func() error, error)
GetHistoricBuildLogs(workflowId int, ciWorkflow *pipelineConfig.CiWorkflow) (map[string]string, error)
DownloadCiWorkflowArtifacts(pipelineId int, buildId int) (*os.File, error)
}
// CATEGORY=CI_BUILDX
type BuildxGlobalFlags struct {
BuildxCacheModeMin bool `env:"BUILDX_CACHE_MODE_MIN" envDefault:"false" description:"To set build cache mode to minimum in buildx" `
AsyncBuildxCacheExport bool `env:"ASYNC_BUILDX_CACHE_EXPORT" envDefault:"false" description:"To enable async container image cache export"`
BuildxInterruptionMaxRetry int `env:"BUILDX_INTERRUPTION_MAX_RETRY" envDefault:"3" description:"Maximum number of retries for buildx builder interruption"`
}
type HandlerServiceImpl struct {
Logger *zap.SugaredLogger
workflowService executor.WorkflowService
ciPipelineMaterialRepository pipelineConfig.CiPipelineMaterialRepository
ciPipelineRepository pipelineConfig.CiPipelineRepository
ciArtifactRepository repository5.CiArtifactRepository
pipelineStageService pipeline2.PipelineStageService
userService user.UserService
ciTemplateService pipeline.CiTemplateReadService
appCrudOperationService app.AppCrudOperationService
envRepository repository6.EnvironmentRepository
appRepository appRepository.AppRepository
customTagService pipeline2.CustomTagService
config *types.CiConfig
scopedVariableManager variables.ScopedVariableManager
ciCdPipelineOrchestrator pipeline2.CiCdPipelineOrchestrator
buildxGlobalFlags *BuildxGlobalFlags
attributeService attributes.AttributesService
pluginInputVariableParser pipeline2.PluginInputVariableParser
globalPluginService plugin.GlobalPluginService
ciService pipeline2.CiService
ciWorkflowRepository pipelineConfig.CiWorkflowRepository
gitSensorClient gitSensor.Client
ciLogService pipeline2.CiLogService
blobConfigStorageService pipeline2.BlobStorageConfigService
clusterService cluster.ClusterService
envService environment.EnvironmentService
K8sUtil *k8s.K8sServiceImpl
asyncRunnable *async.Runnable
workflowTriggerAuditService auditService.WorkflowTriggerAuditService
}
func NewHandlerServiceImpl(Logger *zap.SugaredLogger, workflowService executor.WorkflowService,
ciPipelineMaterialRepository pipelineConfig.CiPipelineMaterialRepository,
ciPipelineRepository pipelineConfig.CiPipelineRepository,
ciArtifactRepository repository5.CiArtifactRepository,
pipelineStageService pipeline2.PipelineStageService,
userService user.UserService,
ciTemplateService pipeline.CiTemplateReadService,
appCrudOperationService app.AppCrudOperationService,
envRepository repository6.EnvironmentRepository,
appRepository appRepository.AppRepository,
scopedVariableManager variables.ScopedVariableManager,
customTagService pipeline2.CustomTagService,
ciCdPipelineOrchestrator pipeline2.CiCdPipelineOrchestrator, attributeService attributes.AttributesService,
pluginInputVariableParser pipeline2.PluginInputVariableParser,
globalPluginService plugin.GlobalPluginService,
ciService pipeline2.CiService,
ciWorkflowRepository pipelineConfig.CiWorkflowRepository,
gitSensorClient gitSensor.Client,
ciLogService pipeline2.CiLogService,
blobConfigStorageService pipeline2.BlobStorageConfigService,
clusterService cluster.ClusterService,
envService environment.EnvironmentService,
K8sUtil *k8s.K8sServiceImpl,
asyncRunnable *async.Runnable,
workflowTriggerAuditService auditService.WorkflowTriggerAuditService,
) *HandlerServiceImpl {
buildxCacheFlags := &BuildxGlobalFlags{}
err := env.Parse(buildxCacheFlags)
if err != nil {
Logger.Infow("error occurred while parsing BuildxGlobalFlags env,so setting BuildxCacheModeMin and AsyncBuildxCacheExport to default value", "err", err)
}
cis := &HandlerServiceImpl{
Logger: Logger,
workflowService: workflowService,
ciPipelineMaterialRepository: ciPipelineMaterialRepository,
ciPipelineRepository: ciPipelineRepository,
ciArtifactRepository: ciArtifactRepository,
pipelineStageService: pipelineStageService,
userService: userService,
ciTemplateService: ciTemplateService,
appCrudOperationService: appCrudOperationService,
envRepository: envRepository,
appRepository: appRepository,
scopedVariableManager: scopedVariableManager,
customTagService: customTagService,
ciCdPipelineOrchestrator: ciCdPipelineOrchestrator,
buildxGlobalFlags: buildxCacheFlags,
attributeService: attributeService,
pluginInputVariableParser: pluginInputVariableParser,
globalPluginService: globalPluginService,
ciService: ciService,
ciWorkflowRepository: ciWorkflowRepository,
gitSensorClient: gitSensorClient,
ciLogService: ciLogService,
blobConfigStorageService: blobConfigStorageService,
clusterService: clusterService,
envService: envService,
K8sUtil: K8sUtil,
asyncRunnable: asyncRunnable,
workflowTriggerAuditService: workflowTriggerAuditService,
}
config, err := types.GetCiConfig()
if err != nil {
return nil
}
cis.config = config
return cis
}
func (impl *HandlerServiceImpl) HandlePodDeleted(ciWorkflow *pipelineConfig.CiWorkflow) {
if !impl.config.WorkflowRetriesEnabled() {
impl.Logger.Debug("ci workflow retry feature disabled")
return
}
retryCount, refCiWorkflow, err := impl.getRefWorkflowAndCiRetryCount(ciWorkflow)
if err != nil {
impl.Logger.Errorw("error in getRefWorkflowAndCiRetryCount", "ciWorkflowId", ciWorkflow.Id, "err", err)
}
impl.Logger.Infow("re-triggering ci by UpdateCiWorkflowStatusFailedCron", "refCiWorkflowId", refCiWorkflow.Id, "ciWorkflow.Status", ciWorkflow.Status, "ciWorkflow.Message", ciWorkflow.Message, "retryCount", retryCount)
err = impl.reTriggerCi(retryCount, refCiWorkflow)
if err != nil {
impl.Logger.Errorw("error in reTriggerCi", "ciWorkflowId", refCiWorkflow.Id, "workflowStatus", ciWorkflow.Status, "ciWorkflowMessage", "ciWorkflow.Message", "retryCount", retryCount, "err", err)
}
}
func (impl *HandlerServiceImpl) CheckAndReTriggerCI(workflowStatus eventProcessorBean.CiCdStatus) error {
// return if re-trigger feature is disabled
if !impl.config.WorkflowRetriesEnabled() {
impl.Logger.Debug("CI re-trigger is disabled")
return nil
}
status, message, ciWorkFlow, err := impl.extractPodStatusAndWorkflow(workflowStatus)
if err != nil {
impl.Logger.Errorw("error in extractPodStatusAndWorkflow", "err", err)
return err
}
if !executors.CheckIfReTriggerRequired(status, message, ciWorkFlow.Status) {
impl.Logger.Debugw("not re-triggering ci", "status", status, "message", message, "ciWorkflowStatus", ciWorkFlow.Status)
return nil
}
impl.Logger.Debugw("re-triggering ci", "status", status, "message", message, "ciWorkflowStatus", ciWorkFlow.Status, "ciWorkFlowId", ciWorkFlow.Id)
retryCount, refCiWorkflow, err := impl.getRefWorkflowAndCiRetryCount(ciWorkFlow)
if err != nil {
impl.Logger.Errorw("error while getting retry count value for a ciWorkflow", "ciWorkFlowId", ciWorkFlow.Id)
return err
}
err = impl.reTriggerCi(retryCount, refCiWorkflow)
if err != nil {
impl.Logger.Errorw("error in reTriggerCi", "err", err, "status", status, "message", message, "retryCount", retryCount, "ciWorkFlowId", ciWorkFlow.Id)
}
return err
}
func (impl *HandlerServiceImpl) reTriggerCi(retryCount int, refCiWorkflow *pipelineConfig.CiWorkflow) error {
if retryCount >= impl.config.MaxCiWorkflowRetries {
impl.Logger.Infow("maximum retries exhausted for this ciWorkflow", "ciWorkflowId", refCiWorkflow.Id, "retries", retryCount, "configuredRetries", impl.config.MaxCiWorkflowRetries)
return nil
}
impl.Logger.Infow("re-triggering ci for a ci workflow", "ReferenceCiWorkflowId", refCiWorkflow.Id)
// Try to use stored workflow config snapshot for retrigger
err := impl.reTriggerCiFromSnapshot(refCiWorkflow)
if err != nil {
impl.Logger.Errorw("failed to retrigger from snapshot", "ciWorkflowId", refCiWorkflow.Id, "err", err)
return err
}
return nil
}
// reTriggerCiFromSnapshot attempts to retrigger CI using a stored workflow config snapshot
func (impl *HandlerServiceImpl) reTriggerCiFromSnapshot(refCiWorkflow *pipelineConfig.CiWorkflow) error {
impl.Logger.Infow("attempting to retrigger CI from stored snapshot", "refCiWorkflowId", refCiWorkflow.Id)
// Retrieve workflow request from snapshot
workflowRequest, err := impl.workflowTriggerAuditService.GetWorkflowRequestFromSnapshotForRetrigger(refCiWorkflow.Id, types.CI_WORKFLOW_TYPE)
if err != nil {
impl.Logger.Errorw("error retrieving workflow request from snapshot", "ciWorkflowId", refCiWorkflow.Id, "err", err)
return err
}
//create a new CI workflow entry for retrigger
newCiWorkflow, err := impl.createNewCiWorkflowForRetrigger(refCiWorkflow)
if err != nil {
impl.Logger.Errorw("error creating new CI workflow for retrigger", "refCiWorkflowId", refCiWorkflow.Id, "err", err)
return err
}
impl.updateWorkflowRequestForRetrigger(workflowRequest, newCiWorkflow)
ciPipelineMaterialIds := make([]int, 0, len(refCiWorkflow.GitTriggers))
for id, _ := range refCiWorkflow.GitTriggers {
ciPipelineMaterialIds = append(ciPipelineMaterialIds, id)
}
ciMaterials, err := impl.ciPipelineMaterialRepository.GetByIdsIncludeDeleted(ciPipelineMaterialIds)
if err != nil {
impl.Logger.Errorw("error in getting ci Pipeline Materials using ciPipeline Material Ids", "ciPipelineMaterialIds", ciPipelineMaterialIds, "err", err)
return err
}
trigger := &types.CiTriggerRequest{IsRetrigger: true, RetriggerWorkflowRequest: workflowRequest, RetriggerCiWorkflow: newCiWorkflow}
trigger.BuildTriggerObject(refCiWorkflow, ciMaterials, bean6.SYSTEM_USER_ID, true, nil, "")
_, err = impl.triggerCiPipeline(trigger)
if err != nil {
impl.Logger.Errorw("error occurred in re-triggering ciWorkflow", "triggerDetails", trigger, "err", err)
return err
}
impl.Logger.Infow("successfully retriggered CI from snapshot", "originalCiWorkflowId", refCiWorkflow.Id, "newCiWorkflowId", newCiWorkflow.Id)
return nil
}
// createNewCiWorkflowForRetrigger creates a new CI workflow entry for retrigger
func (impl *HandlerServiceImpl) createNewCiWorkflowForRetrigger(refCiWorkflow *pipelineConfig.CiWorkflow) (*pipelineConfig.CiWorkflow, error) {
newCiWorkflow := adaptor.GetCiWorkflowFromRefCiWorkflow(refCiWorkflow, cdWorkflow.WorkflowStarting, bean6.SYSTEM_USER_ID)
err := impl.ciService.SaveCiWorkflowWithStage(newCiWorkflow)
if err != nil {
impl.Logger.Errorw("error saving new CI workflow for retrigger", "newCiWorkflow", newCiWorkflow, "err", err)
return nil, err
}
return newCiWorkflow, nil
}
// updateWorkflowRequestForRetrigger updates dynamic fields in workflow request for retrigger, like workflowId,WorkflowNamePrefix and triggeredBy
func (impl *HandlerServiceImpl) updateWorkflowRequestForRetrigger(workflowRequest *types.WorkflowRequest, newCiWorkflow *pipelineConfig.CiWorkflow) {
// Update only the dynamic fields that need to change for retrigger
workflowRequest.WorkflowId = newCiWorkflow.Id
workflowRequest.WorkflowNamePrefix = fmt.Sprintf("%d-%s", newCiWorkflow.Id, newCiWorkflow.Name)
workflowRequest.TriggeredBy = bean6.SYSTEM_USER_ID
// Keep all other fields from snapshot (CI project details, build configs, etc.) unchanged
// This ensures we use the exact same configuration that was used during the original trigger
}
func (impl *HandlerServiceImpl) HandleCIManual(ciTriggerRequest bean.CiTriggerRequest) (int, error) {
impl.Logger.Debugw("HandleCIManual for pipeline ", "PipelineId", ciTriggerRequest.PipelineId)
commitHashes, runtimeParams, err := impl.buildManualTriggerCommitHashes(ciTriggerRequest)
if err != nil {
return 0, err
}
ciArtifact, err := impl.ciArtifactRepository.GetLatestArtifactTimeByCiPipelineId(ciTriggerRequest.PipelineId)
if err != nil && err != pg.ErrNoRows {
impl.Logger.Errorw("Error in GetLatestArtifactTimeByCiPipelineId", "err", err, "pipelineId", ciTriggerRequest.PipelineId)
return 0, err
}
createdOn := time.Time{}
if err != pg.ErrNoRows {
createdOn = ciArtifact.CreatedOn
}
trigger := &types.CiTriggerRequest{
PipelineId: ciTriggerRequest.PipelineId,
CommitHashes: commitHashes,
CiMaterials: nil,
TriggeredBy: ciTriggerRequest.TriggeredBy,
InvalidateCache: ciTriggerRequest.InvalidateCache,
RuntimeParameters: runtimeParams,
EnvironmentId: ciTriggerRequest.EnvironmentId,
PipelineType: ciTriggerRequest.PipelineType,
CiArtifactLastFetch: createdOn,
}
id, err := impl.triggerCiPipeline(trigger)
if err != nil {
return 0, err
}
return id, nil
}
func (impl *HandlerServiceImpl) HandleCIWebhook(gitCiTriggerRequest bean.GitCiTriggerRequest) (int, error) {
impl.Logger.Debugw("HandleCIWebhook for material ", "material", gitCiTriggerRequest.CiPipelineMaterial)
ciPipeline, err := impl.GetCiPipeline(gitCiTriggerRequest.CiPipelineMaterial.Id)
if err != nil {
impl.Logger.Errorw("err in getting ci_pipeline by ciPipelineMaterialId", "ciPipelineMaterialId", gitCiTriggerRequest.CiPipelineMaterial.Id, "err", err)
return 0, err
}
if ciPipeline.IsManual || ciPipeline.PipelineType == buildCommonBean.LINKED_CD.ToString() {
impl.Logger.Debugw("not handling for manual pipeline or in case of linked cd", "pipelineId", ciPipeline.Id)
return 0, err
}
ciMaterials, err := impl.ciPipelineMaterialRepository.GetByPipelineId(ciPipeline.Id)
if err != nil {
impl.Logger.Errorw("err", "err", err)
return 0, err
}
isValidBuildSequence, err := impl.validateBuildSequence(gitCiTriggerRequest, ciPipeline.Id)
if !isValidBuildSequence {
return 0, errors.New("ignoring older build for ciMaterial " + strconv.Itoa(gitCiTriggerRequest.CiPipelineMaterial.Id) +
" commit " + gitCiTriggerRequest.CiPipelineMaterial.GitCommit.Commit)
}
// updating runtime params
runtimeParams := common.NewRuntimeParameters()
for k, v := range gitCiTriggerRequest.ExtraEnvironmentVariables {
runtimeParams = runtimeParams.AddSystemVariable(k, v)
}
runtimeParams, err = impl.updateRuntimeParamsForAutoCI(ciPipeline.Id, runtimeParams)
if err != nil {
impl.Logger.Errorw("err, updateRuntimeParamsForAutoCI", "ciPipelineId", ciPipeline.Id,
"runtimeParameters", runtimeParams, "err", err)
return 0, err
}
commitHashes, err := impl.buildAutomaticTriggerCommitHashes(ciMaterials, gitCiTriggerRequest)
if err != nil {
return 0, err
}
trigger := &types.CiTriggerRequest{
PipelineId: ciPipeline.Id,
CommitHashes: commitHashes,
CiMaterials: ciMaterials,
TriggeredBy: gitCiTriggerRequest.TriggeredBy,
RuntimeParameters: runtimeParams,
}
id, err := impl.triggerCiPipeline(trigger)
if err != nil {
return 0, err
}
return id, nil
}
func (impl *HandlerServiceImpl) extractPodStatusAndWorkflow(workflowStatus eventProcessorBean.CiCdStatus) (string, string, *pipelineConfig.CiWorkflow, error) {
workflowName, status, _, message, _, _ := pipeline2.ExtractWorkflowStatus(workflowStatus)
if workflowName == "" {
impl.Logger.Errorw("extract workflow status, invalid wf name", "workflowName", workflowName, "status", status, "message", message)
return status, message, nil, errors.New("invalid wf name")
}
workflowId, err := strconv.Atoi(workflowName[:strings.Index(workflowName, "-")])
if err != nil {
impl.Logger.Errorw("extract workflowId, invalid wf name", "workflowName", workflowName, "err", err)
return status, message, nil, err
}
savedWorkflow, err := impl.ciWorkflowRepository.FindById(workflowId)
if err != nil {
impl.Logger.Errorw("cannot get saved wf", "workflowId", workflowId, "err", err)
return status, message, nil, err
}
return status, message, savedWorkflow, err
}
func (impl *HandlerServiceImpl) getRefWorkflowAndCiRetryCount(savedWorkflow *pipelineConfig.CiWorkflow) (int, *pipelineConfig.CiWorkflow, error) {
var err error
if savedWorkflow.ReferenceCiWorkflowId != 0 {
savedWorkflow, err = impl.ciWorkflowRepository.FindById(savedWorkflow.ReferenceCiWorkflowId)
if err != nil {
impl.Logger.Errorw("cannot get saved wf", "err", err)
return 0, savedWorkflow, err
}
}
retryCount, err := impl.ciWorkflowRepository.FindRetriedWorkflowCountByReferenceId(savedWorkflow.Id)
return retryCount, savedWorkflow, err
}
func (impl *HandlerServiceImpl) validateBuildSequence(gitCiTriggerRequest bean.GitCiTriggerRequest, pipelineId int) (bool, error) {
isValid := true
lastTriggeredBuild, err := impl.ciWorkflowRepository.FindLastTriggeredWorkflow(pipelineId)
if !(lastTriggeredBuild.Status == string(v1alpha1.NodePending) || lastTriggeredBuild.Status == string(v1alpha1.NodeRunning)) {
return true, nil
}
if err != nil && !util.IsErrNoRows(err) {
impl.Logger.Errorw("cannot get last build for pipeline", "pipelineId", pipelineId)
return false, err
}
ciPipelineMaterial := gitCiTriggerRequest.CiPipelineMaterial
if ciPipelineMaterial.Type == string(constants.SOURCE_TYPE_BRANCH_FIXED) {
if ciPipelineMaterial.GitCommit.Date.Before(lastTriggeredBuild.GitTriggers[ciPipelineMaterial.Id].Date) {
impl.Logger.Warnw("older commit cannot be built for pipeline", "pipelineId", pipelineId, "ciMaterial", gitCiTriggerRequest.CiPipelineMaterial.Id)
isValid = false
}
}
return isValid, nil
}
func (impl *HandlerServiceImpl) buildAutomaticTriggerCommitHashes(ciMaterials []*pipelineConfig.CiPipelineMaterial, request bean.GitCiTriggerRequest) (map[int]pipelineConfig.GitCommit, error) {
commitHashes := map[int]pipelineConfig.GitCommit{}
for _, ciMaterial := range ciMaterials {
if ciMaterial.Id == request.CiPipelineMaterial.Id || len(ciMaterials) == 1 {
request.CiPipelineMaterial.GitCommit = SetGitCommitValuesForBuildingCommitHash(ciMaterial, request.CiPipelineMaterial.GitCommit)
commitHashes[ciMaterial.Id] = request.CiPipelineMaterial.GitCommit
} else {
// this is possible in case of non Webhook, as there would be only one pipeline material per git material in case of PR
lastCommit, err := impl.getLastSeenCommit(ciMaterial.Id)
if err != nil {
return map[int]pipelineConfig.GitCommit{}, err
}
lastCommit = SetGitCommitValuesForBuildingCommitHash(ciMaterial, lastCommit)
commitHashes[ciMaterial.Id] = lastCommit
}
}
return commitHashes, nil
}
func (impl *HandlerServiceImpl) GetCiPipeline(ciMaterialId int) (*pipelineConfig.CiPipeline, error) {
ciMaterial, err := impl.ciPipelineMaterialRepository.GetById(ciMaterialId)
if err != nil {
return nil, err
}
ciPipeline := ciMaterial.CiPipeline
return ciPipeline, nil
}
func (impl *HandlerServiceImpl) buildManualTriggerCommitHashes(ciTriggerRequest bean.CiTriggerRequest) (map[int]pipelineConfig.GitCommit, *common.RuntimeParameters, error) {
commitHashes := map[int]pipelineConfig.GitCommit{}
runtimeParams := impl.getRuntimeParamsForBuildingManualTriggerHashes(ciTriggerRequest)
for _, ciPipelineMaterial := range ciTriggerRequest.CiPipelineMaterial {
pipeLineMaterialFromDb, err := impl.ciPipelineMaterialRepository.GetById(ciPipelineMaterial.Id)
if err != nil {
impl.Logger.Errorw("err in fetching pipeline material by id", "err", err)
return map[int]pipelineConfig.GitCommit{}, nil, err
}
pipelineType := pipeLineMaterialFromDb.Type
if pipelineType == constants.SOURCE_TYPE_BRANCH_FIXED {
gitCommit, err := impl.BuildManualTriggerCommitHashesForSourceTypeBranchFix(ciPipelineMaterial, pipeLineMaterialFromDb)
if err != nil {
impl.Logger.Errorw("err", "err", err)
return map[int]pipelineConfig.GitCommit{}, nil, err
}
commitHashes[ciPipelineMaterial.Id] = gitCommit
} else if pipelineType == constants.SOURCE_TYPE_WEBHOOK {
gitCommit, extraEnvVariables, err := impl.BuildManualTriggerCommitHashesForSourceTypeWebhook(ciPipelineMaterial, pipeLineMaterialFromDb)
if err != nil {
impl.Logger.Errorw("err", "err", err)
return map[int]pipelineConfig.GitCommit{}, nil, err
}
commitHashes[ciPipelineMaterial.Id] = gitCommit
for key, value := range extraEnvVariables {
runtimeParams = runtimeParams.AddSystemVariable(key, value)
}
}
}
return commitHashes, runtimeParams, nil
}
func (impl *HandlerServiceImpl) BuildManualTriggerCommitHashesForSourceTypeBranchFix(ciPipelineMaterial bean.CiPipelineMaterial, pipeLineMaterialFromDb *pipelineConfig.CiPipelineMaterial) (pipelineConfig.GitCommit, error) {
commitMetadataRequest := &gitSensor.CommitMetadataRequest{
PipelineMaterialId: ciPipelineMaterial.Id,
GitHash: ciPipelineMaterial.GitCommit.Commit,
GitTag: ciPipelineMaterial.GitTag,
}
gitCommitResponse, err := impl.gitSensorClient.GetCommitMetadataForPipelineMaterial(context.Background(), commitMetadataRequest)
if err != nil {
impl.Logger.Errorw("err in fetching commit metadata", "commitMetadataRequest", commitMetadataRequest, "err", err)
return pipelineConfig.GitCommit{}, err
}
if gitCommitResponse == nil {
return pipelineConfig.GitCommit{}, errors.New("commit not found")
}
gitCommit := pipelineConfig.GitCommit{
Commit: gitCommitResponse.Commit,
Author: gitCommitResponse.Author,
Date: gitCommitResponse.Date,
Message: gitCommitResponse.Message,
Changes: gitCommitResponse.Changes,
GitRepoName: pipeLineMaterialFromDb.GitMaterial.Name[strings.Index(pipeLineMaterialFromDb.GitMaterial.Name, "-")+1:],
GitRepoUrl: pipeLineMaterialFromDb.GitMaterial.Url,
CiConfigureSourceValue: pipeLineMaterialFromDb.Value,
CiConfigureSourceType: pipeLineMaterialFromDb.Type,
}
return gitCommit, nil
}
func (impl *HandlerServiceImpl) BuildManualTriggerCommitHashesForSourceTypeWebhook(ciPipelineMaterial bean.CiPipelineMaterial, pipeLineMaterialFromDb *pipelineConfig.CiPipelineMaterial) (pipelineConfig.GitCommit, map[string]string, error) {
webhookDataInput := ciPipelineMaterial.GitCommit.WebhookData
// fetch webhook data on the basis of Id
webhookDataRequest := &gitSensor.WebhookDataRequest{
Id: webhookDataInput.Id,
CiPipelineMaterialId: ciPipelineMaterial.Id,
}
webhookAndCiData, err := impl.gitSensorClient.GetWebhookData(context.Background(), webhookDataRequest)
if err != nil {
impl.Logger.Errorw("err", "err", err)
return pipelineConfig.GitCommit{}, nil, err
}
webhookData := webhookAndCiData.WebhookData
// if webhook event is of merged type, then fetch latest commit for target branch
if webhookData.EventActionType == bean.WEBHOOK_EVENT_MERGED_ACTION_TYPE {
// get target branch name from webhook
targetBranchName := webhookData.Data[bean.WEBHOOK_SELECTOR_TARGET_BRANCH_NAME_NAME]
if targetBranchName == "" {
impl.Logger.Error("target branch not found from webhook data")
return pipelineConfig.GitCommit{}, nil, err
}
// get latest commit hash for target branch
latestCommitMetadataRequest := &gitSensor.CommitMetadataRequest{
PipelineMaterialId: ciPipelineMaterial.Id,
BranchName: targetBranchName,
}
latestCommit, err := impl.gitSensorClient.GetCommitMetadata(context.Background(), latestCommitMetadataRequest)
if err != nil {
impl.Logger.Errorw("err", "err", err)
return pipelineConfig.GitCommit{}, nil, err
}
// update webhookData (local) with target latest hash
webhookData.Data[bean.WEBHOOK_SELECTOR_TARGET_CHECKOUT_NAME] = latestCommit.Commit
}
// build git commit
gitCommit := pipelineConfig.GitCommit{
GitRepoName: pipeLineMaterialFromDb.GitMaterial.Name[strings.Index(pipeLineMaterialFromDb.GitMaterial.Name, "-")+1:],
GitRepoUrl: pipeLineMaterialFromDb.GitMaterial.Url,
CiConfigureSourceValue: pipeLineMaterialFromDb.Value,
CiConfigureSourceType: pipeLineMaterialFromDb.Type,
WebhookData: pipelineConfig.WebhookData{
Id: int(webhookData.Id),
EventActionType: webhookData.EventActionType,
Data: webhookData.Data,
},
}
return gitCommit, webhookAndCiData.ExtraEnvironmentVariables, nil
}
func (impl *HandlerServiceImpl) getLastSeenCommit(ciMaterialId int) (pipelineConfig.GitCommit, error) {
var materialIds []int
materialIds = append(materialIds, ciMaterialId)
headReq := &gitSensor.HeadRequest{
MaterialIds: materialIds,
}
res, err := impl.gitSensorClient.GetHeadForPipelineMaterials(context.Background(), headReq)
if err != nil {
return pipelineConfig.GitCommit{}, err
}
if len(res) == 0 {
return pipelineConfig.GitCommit{}, errors.New("received empty response")
}
gitCommit := pipelineConfig.GitCommit{
Commit: res[0].GitCommit.Commit,
Author: res[0].GitCommit.Author,
Date: res[0].GitCommit.Date,
Message: res[0].GitCommit.Message,
Changes: res[0].GitCommit.Changes,
}
return gitCommit, nil
}
func SetGitCommitValuesForBuildingCommitHash(ciMaterial *pipelineConfig.CiPipelineMaterial, oldGitCommit pipelineConfig.GitCommit) pipelineConfig.GitCommit {
newGitCommit := oldGitCommit
newGitCommit.CiConfigureSourceType = ciMaterial.Type
newGitCommit.CiConfigureSourceValue = ciMaterial.Value
newGitCommit.GitRepoUrl = ciMaterial.GitMaterial.Url
newGitCommit.GitRepoName = ciMaterial.GitMaterial.Name[strings.Index(ciMaterial.GitMaterial.Name, "-")+1:]
return newGitCommit
}
func (impl *HandlerServiceImpl) fetchVariableSnapshotForCiRetrigger(trigger *types.CiTriggerRequest) (map[string]string, error) {
scope := resourceQualifiers.Scope{
AppId: trigger.RetriggerWorkflowRequest.AppId,
}
request := pipelineConfigBean.NewBuildPrePostStepDataReq(trigger.RetriggerWorkflowRequest.PipelineId, pipelineConfigBean.CiStage, scope)
request = updateBuildPrePostStepDataReq(request, trigger)
prePostAndRefPluginResponse, err := impl.pipelineStageService.BuildPrePostAndRefPluginStepsDataForWfRequest(request)
if err != nil {
impl.Logger.Errorw("error in getting pre steps data for wf request", "ciPipelineId", trigger.RetriggerWorkflowRequest.PipelineId, "err", err)
dbErr := impl.markCurrentCiWorkflowFailed(trigger.RetriggerCiWorkflow, err)
if dbErr != nil {
impl.Logger.Errorw("saving workflow error", "err", dbErr)
}
return nil, err
}
return prePostAndRefPluginResponse.VariableSnapshot, nil
}
func (impl *HandlerServiceImpl) prepareCiWfRequest(trigger *types.CiTriggerRequest) (map[string]string, *pipelineConfig.CiWorkflow, *types.WorkflowRequest, error) {
var variableSnapshot map[string]string
var savedCiWf *pipelineConfig.CiWorkflow
var workflowRequest *types.WorkflowRequest
var err error
if trigger.IsRetrigger {
variableSnapshot, err = impl.fetchVariableSnapshotForCiRetrigger(trigger)
if err != nil {
impl.Logger.Errorw("error in fetchVariableSnapshotForCiRetrigger", "triggerRequest", trigger, "err", err)
return nil, nil, nil, err
}
savedCiWf, workflowRequest = trigger.RetriggerCiWorkflow, trigger.RetriggerWorkflowRequest
if trigger.RetriggerCiWorkflow != nil {
workflowRequest.ReferenceCiWorkflowId = trigger.RetriggerCiWorkflow.ReferenceCiWorkflowId
}
workflowRequest.IsReTrigger = true
} else {
variableSnapshot, savedCiWf, workflowRequest, err = impl.StartCiWorkflowAndPrepareWfRequest(trigger)
if err != nil {
impl.Logger.Errorw("error in starting ci workflow and preparing wf request", "triggerRequest", trigger, "err", err)
return nil, nil, nil, err
}
workflowRequest.CiPipelineType = trigger.PipelineType
}
return variableSnapshot, savedCiWf, workflowRequest, nil
}
func (impl *HandlerServiceImpl) triggerCiPipeline(trigger *types.CiTriggerRequest) (int, error) {
variableSnapshot, savedCiWf, workflowRequest, err := impl.prepareCiWfRequest(trigger)
if err != nil {
impl.Logger.Errorw("error in preparing wf request", "triggerRequest", trigger, "err", err)
return 0, err
}
err = impl.executeCiPipeline(workflowRequest)
if err != nil {
impl.Logger.Errorw("error in executing ci pipeline", "err", err)
dbErr := impl.markCurrentCiWorkflowFailed(savedCiWf, err)
if dbErr != nil {
impl.Logger.Errorw("update ci workflow error", "err", dbErr)
}
return 0, err
}
impl.Logger.Debugw("ci triggered", " pipeline ", trigger.PipelineId)
var variableSnapshotHistories = sliceUtil.GetBeansPtr(
repository4.GetSnapshotBean(savedCiWf.Id, repository4.HistoryReferenceTypeCIWORKFLOW, variableSnapshot))
if len(variableSnapshotHistories) > 0 {
err = impl.scopedVariableManager.SaveVariableHistoriesForTrigger(variableSnapshotHistories, trigger.TriggeredBy)
if err != nil {
impl.Logger.Errorf("Not able to save variable snapshot for CI trigger %s", err)
}
}
middleware.CiTriggerCounter.WithLabelValues(workflowRequest.AppName, workflowRequest.PipelineName).Inc()
runnableFunc := func() {
impl.ciService.WriteCITriggerEvent(trigger, workflowRequest)
}
impl.asyncRunnable.Execute(runnableFunc)
return savedCiWf.Id, err
}
func (impl *HandlerServiceImpl) GetCiMaterials(pipelineId int, ciMaterials []*pipelineConfig.CiPipelineMaterial) ([]*pipelineConfig.CiPipelineMaterial, error) {
if !(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 *HandlerServiceImpl) StartCiWorkflowAndPrepareWfRequest(trigger *types.CiTriggerRequest) (map[string]string, *pipelineConfig.CiWorkflow, *types.WorkflowRequest, error) {
impl.Logger.Debugw("ci pipeline manual trigger", "request", trigger)
ciMaterials, err := impl.GetCiMaterials(trigger.PipelineId, trigger.CiMaterials)
if err != nil {
impl.Logger.Errorw("error in getting ci materials", "pipelineId", trigger.PipelineId, "ciMaterials", trigger.CiMaterials, "err", err)
return nil, nil, nil, err
}
ciPipelineScripts, err := impl.ciPipelineRepository.FindCiScriptsByCiPipelineId(trigger.PipelineId)
if err != nil && !util.IsErrNoRows(err) {
impl.Logger.Errorw("error in getting ci script by pipeline id", "pipelineId", trigger.PipelineId, "err", err)
return nil, nil, nil, err
}
var pipeline *pipelineConfig.CiPipeline
for _, m := range ciMaterials {
pipeline = m.CiPipeline
break
}
scope := resourceQualifiers.Scope{
AppId: pipeline.App.Id,
PipelineId: pipeline.Id, // Added pipeline ID for pipeline-level infra profile support
}
ciWorkflowConfigNamespace := impl.config.GetDefaultNamespace()
envModal, isJob, err := impl.getEnvironmentForJob(pipeline, trigger)
if err != nil {
impl.Logger.Errorw("error in getting environment for job", "pipelineId", trigger.PipelineId, "err", err)
return nil, nil, nil, err
}
if isJob && envModal != nil {
err = impl.checkArgoSetupRequirement(envModal)
if err != nil {
impl.Logger.Errorw("error in checking argo setup requirement", "envModal", envModal, "err", err)
return nil, nil, nil, err
}
ciWorkflowConfigNamespace = envModal.Namespace
// This will be populated for jobs running in selected environment
scope.EnvId = envModal.Id
scope.ClusterId = envModal.ClusterId
scope.SystemMetadata = &resourceQualifiers.SystemMetadata{
EnvironmentName: envModal.Name,
ClusterName: envModal.Cluster.ClusterName,
Namespace: envModal.Namespace,
}
}
if scope.SystemMetadata == nil {
scope.SystemMetadata = &resourceQualifiers.SystemMetadata{
Namespace: ciWorkflowConfigNamespace,
AppName: pipeline.App.AppName,
}
}
savedCiWf, err := impl.saveNewWorkflowForCITrigger(pipeline, ciWorkflowConfigNamespace, trigger.CommitHashes, trigger.TriggeredBy, ciMaterials, trigger.EnvironmentId, isJob, trigger.ReferenceCiWorkflowId)
if err != nil {
impl.Logger.Errorw("could not save new workflow", "err", err)
return nil, nil, nil, err
}
// preCiSteps, postCiSteps, refPluginsData, err := impl.pipelineStageService.BuildPrePostAndRefPluginStepsDataForWfRequest(pipeline.Id, ciEvent)
request := pipelineConfigBean.NewBuildPrePostStepDataReq(pipeline.Id, pipelineConfigBean.CiStage, scope)
request = updateBuildPrePostStepDataReq(request, trigger)
prePostAndRefPluginResponse, err := impl.pipelineStageService.BuildPrePostAndRefPluginStepsDataForWfRequest(request)
if err != nil {
impl.Logger.Errorw("error in getting pre steps data for wf request", "err", err, "ciPipelineId", pipeline.Id)
dbErr := impl.markCurrentCiWorkflowFailed(savedCiWf, err)
if dbErr != nil {
impl.Logger.Errorw("saving workflow error", "err", dbErr)
}
return nil, nil, nil, err
}
preCiSteps := prePostAndRefPluginResponse.PreStageSteps
postCiSteps := prePostAndRefPluginResponse.PostStageSteps
refPluginsData := prePostAndRefPluginResponse.RefPluginData
variableSnapshot := prePostAndRefPluginResponse.VariableSnapshot
if len(preCiSteps) == 0 && isJob {
errMsg := fmt.Sprintf("No tasks are configured in this job pipeline")
validationErr := util.NewApiError(http.StatusNotFound, errMsg, errMsg)
return nil, nil, nil, validationErr
}
// get env variables of git trigger data and add it in the extraEnvVariables
gitTriggerEnvVariables, _, err := impl.ciCdPipelineOrchestrator.GetGitCommitEnvVarDataForCICDStage(savedCiWf.GitTriggers)
if err != nil {
impl.Logger.Errorw("error in getting gitTrigger env data for stage", "gitTriggers", savedCiWf.GitTriggers, "err", err)
return nil, nil, nil, err
}
for k, v := range gitTriggerEnvVariables {
trigger.RuntimeParameters = trigger.RuntimeParameters.AddSystemVariable(k, v)
}
workflowRequest, err := impl.buildWfRequestForCiPipeline(pipeline, trigger, ciMaterials, savedCiWf, ciWorkflowConfigNamespace, ciPipelineScripts, preCiSteps, postCiSteps, refPluginsData, isJob)
if err != nil {
impl.Logger.Errorw("make workflow req", "err", err)
return nil, nil, nil, err
}
err = impl.handleRuntimeParamsValidations(trigger, ciMaterials, workflowRequest)
if err != nil {
savedCiWf.Status = cdWorkflow.WorkflowAborted
savedCiWf.Message = err.Error()
err1 := impl.ciService.UpdateCiWorkflowWithStage(savedCiWf)
if err1 != nil {
impl.Logger.Errorw("could not save workflow, after failing due to conflicting image tag")
}
return nil, nil, nil, err
}
workflowRequest.Scope = scope
workflowRequest.AppId = pipeline.AppId
workflowRequest.Env = envModal
if isJob {
workflowRequest.Type = pipelineConfigBean.JOB_WORKFLOW_PIPELINE_TYPE
} else {
workflowRequest.Type = pipelineConfigBean.CI_WORKFLOW_PIPELINE_TYPE
}
workflowRequest, err = impl.updateWorkflowRequestWithBuildxFlags(workflowRequest, scope)
if err != nil {
impl.Logger.Errorw("error, updateWorkflowRequestWithBuildxFlags", "workflowRequest", workflowRequest, "err", err)
return nil, nil, nil, err
}
if impl.canSetK8sDriverData(workflowRequest) {
err = impl.setBuildxK8sDriverData(workflowRequest)
if err != nil {
impl.Logger.Errorw("error in setBuildxK8sDriverData", "BUILDX_K8S_DRIVER_OPTIONS", impl.config.BuildxK8sDriverOptions, "err", err)
return nil, nil, nil, err
}
}
savedCiWf.LogLocation = fmt.Sprintf("%s/%s/main.log", impl.config.GetDefaultBuildLogsKeyPrefix(), workflowRequest.WorkflowNamePrefix)
err = impl.updateCiWorkflow(workflowRequest, savedCiWf)
appLabels, err := impl.appCrudOperationService.GetLabelsByAppId(pipeline.AppId)
if err != nil {
impl.Logger.Errorw("error in getting labels by appId", "appId", pipeline.AppId, "err", err)
return nil, nil, nil, err
}
workflowRequest.AppLabels = appLabels
workflowRequest = impl.updateWorkflowRequestWithEntSupportData(workflowRequest)
return variableSnapshot, savedCiWf, workflowRequest, nil
}
func (impl *HandlerServiceImpl) setBuildxK8sDriverData(workflowRequest *types.WorkflowRequest) error {
dockerBuildConfig := workflowRequest.CiBuildConfig.DockerBuildConfig
k8sDriverOptions, err := impl.getK8sDriverOptions(workflowRequest, dockerBuildConfig.TargetPlatform)
if err != nil {
impl.Logger.Errorw("error in parsing BUILDX_K8S_DRIVER_OPTIONS from the devtron-cm", "err", err)
}
dockerBuildConfig.BuildxK8sDriverOptions = k8sDriverOptions
return nil
}
func (impl *HandlerServiceImpl) getEnvironmentForJob(pipeline *pipelineConfig.CiPipeline, trigger *types.CiTriggerRequest) (*repository6.Environment, bool, error) {
app, err := impl.appRepository.FindById(pipeline.AppId)
if err != nil {
impl.Logger.Errorw("could not find app", "err", err)
return nil, false, err
}
var env *repository6.Environment
isJob := false
if app.AppType == helper.Job {
isJob = true
if trigger.EnvironmentId != 0 {
env, err = impl.envRepository.FindById(trigger.EnvironmentId)
if err != nil {
impl.Logger.Errorw("could not find environment", "err", err)
return nil, isJob, err
}
return env, isJob, nil
}
}
return nil, isJob, nil
}
// TODO: Send all trigger data
func (impl *HandlerServiceImpl) BuildPayload(trigger types.CiTriggerRequest, pipeline *pipelineConfig.CiPipeline) *client.Payload {
payload := &client.Payload{}
payload.AppName = pipeline.App.AppName
payload.PipelineName = pipeline.Name
return payload
}
func (impl *HandlerServiceImpl) saveNewWorkflowForCITrigger(pipeline *pipelineConfig.CiPipeline, ciWorkflowConfigNamespace string,
commitHashes map[int]pipelineConfig.GitCommit, userId int32, ciMaterials []*pipelineConfig.CiPipelineMaterial, EnvironmentId int, isJob bool, refCiWorkflowId int) (*pipelineConfig.CiWorkflow, error) {
isCiTriggerBlocked, err := impl.checkIfCITriggerIsBlocked(pipeline, ciMaterials, isJob)
if err != nil {
impl.Logger.Errorw("error, checkIfCITriggerIsBlocked", "pipelineId", pipeline.Id, "err", err)
return &pipelineConfig.CiWorkflow{}, err
}
ciWorkflow := &pipelineConfig.CiWorkflow{
Name: pipeline.Name + "-" + strconv.Itoa(pipeline.Id),
Status: cdWorkflow.WorkflowStarting, // starting CIStage
Message: "",
StartedOn: time.Now(),
CiPipelineId: pipeline.Id,
Namespace: impl.config.GetDefaultNamespace(),
BlobStorageEnabled: impl.config.BlobStorageEnabled,
GitTriggers: commitHashes,
LogLocation: "",
TriggeredBy: userId,
ReferenceCiWorkflowId: refCiWorkflowId,
ExecutorType: impl.config.GetWorkflowExecutorType(),
}
if isJob {
ciWorkflow.Namespace = ciWorkflowConfigNamespace
ciWorkflow.EnvironmentId = EnvironmentId
}
if isCiTriggerBlocked {
return impl.handleWFIfCITriggerIsBlocked(ciWorkflow)
}
err = impl.ciService.SaveCiWorkflowWithStage(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 *HandlerServiceImpl) executeCiPipeline(workflowRequest *types.WorkflowRequest) error {
_, _, err := impl.workflowService.SubmitWorkflow(workflowRequest)
if err != nil {
impl.Logger.Errorw("workflow error", "err", err)
return err
}
return nil
}
func (impl *HandlerServiceImpl) buildS3ArtifactLocation(ciWorkflowConfigLogsBucket string, savedWf *pipelineConfig.CiWorkflow) (string, string, string) {
ciArtifactLocationFormat := impl.config.GetArtifactLocationFormat()
ArtifactLocation := fmt.Sprintf("s3://"+path.Join(ciWorkflowConfigLogsBucket, ciArtifactLocationFormat), savedWf.Id, savedWf.Id)
artifactFileName := fmt.Sprintf(ciArtifactLocationFormat, savedWf.Id, savedWf.Id)
return ArtifactLocation, ciWorkflowConfigLogsBucket, artifactFileName
}
func (impl *HandlerServiceImpl) buildDefaultArtifactLocation(savedWf *pipelineConfig.CiWorkflow) string {
ciArtifactLocationFormat := impl.config.GetArtifactLocationFormat()
ArtifactLocation := fmt.Sprintf(ciArtifactLocationFormat, savedWf.Id, savedWf.Id)
return ArtifactLocation
}
func (impl *HandlerServiceImpl) buildWfRequestForCiPipeline(pipeline *pipelineConfig.CiPipeline, trigger *types.CiTriggerRequest, ciMaterials []*pipelineConfig.CiPipelineMaterial, savedWf *pipelineConfig.CiWorkflow, ciWorkflowConfigNamespace string, ciPipelineScripts []*pipelineConfig.CiPipelineScript, preCiSteps []*pipelineConfigBean.StepObject, postCiSteps []*pipelineConfigBean.StepObject, refPluginsData []*pipelineConfigBean.RefPluginObject, isJob bool) (*types.WorkflowRequest, error) {
var ciProjectDetails []pipelineConfigBean.CiProjectDetails
commitHashes := trigger.CommitHashes