-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEventHelper.go
773 lines (706 loc) · 38.1 KB
/
EventHelper.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
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
/*
* Copyright (c) 2024. Devtron Inc.
*
* 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 helper
import (
"crypto/tls"
"encoding/json"
"fmt"
bean2 "github.com/devtron-labs/common-lib/imageScan/bean"
"github.com/devtron-labs/common-lib/utils/remoteConnection/bean"
"log"
"net/http"
"strings"
"time"
"github.com/caarlos0/env"
"github.com/devtron-labs/ci-runner/pubsub"
"github.com/devtron-labs/ci-runner/util"
blobStorage "github.com/devtron-labs/common-lib/blob-storage"
pubSub "github.com/devtron-labs/common-lib/pubsub-lib"
"github.com/go-resty/resty/v2"
)
type TestExecutorImageProperties struct {
ImageName string `json:"imageName,omitempty"`
Arg string `json:"arg,omitempty"`
}
type CiBuildType string
const (
SELF_DOCKERFILE_BUILD_TYPE CiBuildType = "self-dockerfile-build"
MANAGED_DOCKERFILE_BUILD_TYPE CiBuildType = "managed-dockerfile-build"
BUILD_SKIP_BUILD_TYPE CiBuildType = "skip-build"
BUILDPACK_BUILD_TYPE CiBuildType = "buildpack-build"
)
const CI_JOB string = "CI_JOB"
type CiBuildConfigBean struct {
CiBuildType CiBuildType `json:"ciBuildType"`
DockerBuildConfig *DockerBuildConfig `json:"dockerBuildConfig,omitempty"`
BuildPackConfig *BuildPackConfig `json:"buildPackConfig"`
PipelineType string `json:"pipelineType"`
}
type DockerBuildConfig struct {
DockerfilePath string `json:"dockerfileRelativePath,omitempty" validate:"required"`
DockerfileContent string `json:"DockerfileContent"`
Args map[string]string `json:"args,omitempty"`
DockerBuildOptions map[string]string `json:"dockerBuildOptions"`
TargetPlatform string `json:"targetPlatform,omitempty"`
BuildContext string `json:"buildContext,omitempty"`
UseBuildx bool `json:"useBuildx"`
BuildxProvenanceMode string `json:"buildxProvenanceMode"`
BuildxK8sDriverOptions []map[string]string `json:"buildxK8SDriverOptions"`
//ent only
BuildxDriverImage string `json:"buildxDriverImage"`
}
type BuildPackConfig struct {
BuilderId string `json:"builderId"`
Language string `json:"language"`
LanguageVersion string `json:"languageVersion"`
BuildPacks []string `json:"buildPacks"`
Args map[string]string `json:"args"`
ProjectPath string `json:"projectPath"`
}
type BuildpackVersionConfig struct {
BuilderPrefix string `json:"builderPrefix"`
Language string `json:"language"`
FileName string `json:"fileName"`
FileOverride bool `json:"fileOverride"`
EntryRegex string `json:"entryRegex"`
}
type CommonWorkflowRequest struct {
WorkflowNamePrefix string `json:"workflowNamePrefix"`
PipelineName string `json:"pipelineName"`
PipelineId int `json:"pipelineId"`
DockerImageTag string `json:"dockerImageTag"`
DockerRegistryId string `json:"dockerRegistryId"`
DockerRegistryType string `json:"dockerRegistryType"`
DockerRegistryURL string `json:"dockerRegistryURL"`
DockerRegistryConnectionConfig *bean.RemoteConnectionConfigBean `json:"dockerRegistryConnectionConfig"`
DockerConnection string `json:"dockerConnection"`
DockerCert string `json:"dockerCert"`
DockerRepository string `json:"dockerRepository"`
CheckoutPath string `json:"checkoutPath"`
DockerUsername string `json:"dockerUsername"`
DockerPassword string `json:"dockerPassword"`
AwsRegion string `json:"awsRegion"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
CiCacheLocation string `json:"ciCacheLocation"`
CiCacheRegion string `json:"ciCacheRegion"`
CiCacheFileName string `json:"ciCacheFileName"`
CiProjectDetails []CiProjectDetails `json:"ciProjectDetails"`
ActiveDeadlineSeconds int64 `json:"activeDeadlineSeconds"`
CiImage string `json:"ciImage"`
Namespace string `json:"namespace"`
WorkflowId int `json:"workflowId"`
TriggeredBy int `json:"triggeredBy"`
CacheLimit int64 `json:"cacheLimit"`
BeforeDockerBuildScripts []*Task `json:"beforeDockerBuildScripts"`
AfterDockerBuildScripts []*Task `json:"afterDockerBuildScripts"`
CiArtifactLocation string `json:"ciArtifactLocation"`
CiArtifactBucket string `json:"ciArtifactBucket"`
CiArtifactFileName string `json:"ciArtifactFileName"`
CiArtifactRegion string `json:"ciArtifactRegion"`
ScanEnabled bool `json:"scanEnabled"`
CloudProvider blobStorage.BlobStorageType `json:"cloudProvider"`
BlobStorageConfigured bool `json:"blobStorageConfigured"`
BlobStorageS3Config *blobStorage.BlobStorageS3Config `json:"blobStorageS3Config"`
AzureBlobConfig *blobStorage.AzureBlobConfig `json:"azureBlobConfig"`
GcpBlobConfig *blobStorage.GcpBlobConfig `json:"gcpBlobConfig"`
BlobStorageLogsKey string `json:"blobStorageLogsKey"`
InAppLoggingEnabled bool `json:"inAppLoggingEnabled"`
DefaultAddressPoolBaseCidr string `json:"defaultAddressPoolBaseCidr"`
DefaultAddressPoolSize int `json:"defaultAddressPoolSize"`
PreCiSteps []*StepObject `json:"preCiSteps"`
PostCiSteps []*StepObject `json:"postCiSteps"`
RefPlugins []*RefPluginObject `json:"refPlugins"`
AppName string `json:"appName"`
TriggerByAuthor string `json:"triggerByAuthor"`
CiBuildConfig *CiBuildConfigBean `json:"ciBuildConfig"`
CiBuildDockerMtuValue int `json:"ciBuildDockerMtuValue"`
IgnoreDockerCachePush bool `json:"ignoreDockerCachePush"`
IgnoreDockerCachePull bool `json:"ignoreDockerCachePull"`
CacheInvalidate bool `json:"cacheInvalidate"`
IsPvcMounted bool `json:"IsPvcMounted"`
RuntimeEnvironmentVariables map[string]string `json:"runtimeEnvironmentVariables"`
SystemEnvironmentVariables map[string]string `json:"systemEnvironmentVariables"`
EnableBuildContext bool `json:"enableBuildContext"`
AppId int `json:"appId"`
EnvironmentId int `json:"environmentId"`
OrchestratorHost string `json:"orchestratorHost"`
OrchestratorToken string `json:"orchestratorToken"`
IsExtRun bool `json:"isExtRun"`
ImageRetryCount int `json:"imageRetryCount"`
ImageRetryInterval int `json:"imageRetryInterval"`
ExtBlobStorageCmName string `json:"extBlobStorageCmName"`
ExtBlobStorageSecretName string `json:"extBlobStorageSecretName"`
UseExternalClusterBlob bool `json:"useExternalClusterBlob"`
ImageScanMaxRetries int `json:"imageScanMaxRetries,omitempty"`
ImageScanRetryDelay int `json:"imageScanRetryDelay,omitempty"`
ShouldPullDigest bool `json:"shouldPullDigest,omitempty"`
EnableSecretMasking bool `json:"enableSecretMasking"`
// Data from CD Workflow service
WorkflowRunnerId int `json:"workflowRunnerId"`
CdPipelineId int `json:"cdPipelineId"`
StageYaml string `json:"stageYaml"`
ArtifactLocation string `json:"artifactLocation"`
CiArtifactDTO CiArtifactDTO `json:"ciArtifactDTO"`
CdImage string `json:"cdImage"`
StageType string `json:"stageType"`
CdCacheLocation string `json:"cdCacheLocation"`
CdCacheRegion string `json:"cdCacheRegion"`
WorkflowPrefixForLog string `json:"workflowPrefixForLog"`
DeploymentTriggeredBy string `json:"deploymentTriggeredBy,omitempty"`
DeploymentTriggerTime time.Time `json:"deploymentTriggerTime,omitempty"`
DeploymentReleaseCounter int `json:"deploymentReleaseCounter,omitempty"`
PrePostDeploySteps []*StepObject `json:"prePostDeploySteps"`
TaskYaml *TaskYaml `json:"-"`
IsVirtualExecution bool `json:"isVirtualExecution"`
CiArtifactLastFetch time.Time `json:"ciArtifactLastFetch"`
CiPipelineType string `json:"CiPipelineType"`
RegistryDestinationImageMap map[string][]string `json:"registryDestinationImageMap"`
RegistryCredentialMap map[string]RegistryCredentials `json:"registryCredentialMap"`
PluginArtifactStage string `json:"pluginArtifactStage"`
PushImageBeforePostCI bool `json:"pushImageBeforePostCI"`
IntermediateDockerRegistryUrl string `json:"-"` // this URL will be used for all operations and can be mutated
BuildxCacheModeMin bool `json:"buildxCacheModeMin"`
AsyncBuildxCacheExport bool `json:"asyncBuildxCacheExport"`
UseDockerApiToGetDigest bool `json:"useDockerApiToGetDigest"`
HostUrl string `json:"hostUrl"`
ImageScanningSteps []*ImageScanningSteps `json:"imageScanningSteps,omitempty"`
ExecuteImageScanningVia bean2.ExecutionMedium `json:"executeImageScanningVia,omitempty"`
AwsInspectorConfig string `json:"awsInspectorConfig,omitempty"`
}
func (c *CommonWorkflowRequest) IsPreCdStage() bool {
return c.StageType == string(STEP_TYPE_PRE)
}
func (c *CommonWorkflowRequest) IsPostCdStage() bool {
return c.StageType == string(STEP_TYPE_POST)
}
func (c *CommonWorkflowRequest) GetCdStageType() PipelineType {
if c.StageType == string(STEP_TYPE_PRE) {
return PRE_CD
} else if c.StageType == string(STEP_TYPE_POST) {
return POST_CD
}
return ""
}
func (c *CommonWorkflowRequest) GetCloudHelperBaseConfig(blobStorageObjectType string) *util.CloudHelperBaseConfig {
return &util.CloudHelperBaseConfig{
StorageModuleConfigured: c.BlobStorageConfigured,
BlobStorageLogKey: c.BlobStorageLogsKey,
CloudProvider: c.CloudProvider,
UseExternalClusterBlob: c.UseExternalClusterBlob,
BlobStorageS3Config: c.BlobStorageS3Config,
AzureBlobConfig: c.AzureBlobConfig,
GcpBlobConfig: c.GcpBlobConfig,
BlobStorageObjectType: blobStorageObjectType,
}
}
type CiRequest struct {
CiProjectDetails []CiProjectDetails `json:"ciProjectDetails"`
DockerImageTag string `json:"dockerImageTag"`
DockerRegistryId string `json:"dockerRegistryId"`
DockerRegistryType string `json:"dockerRegistryType"`
DockerRegistryURL string `json:"dockerRegistryURL"`
DockerConnection string `json:"dockerConnection"`
DockerCert string `json:"dockerCert"`
DockerRepository string `json:"dockerRepository"`
CheckoutPath string `json:"checkoutPath"`
DockerUsername string `json:"dockerUsername"`
DockerPassword string `json:"dockerPassword"`
AwsRegion string `json:"awsRegion"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
CiCacheLocation string `json:"ciCacheLocation"`
CiArtifactLocation string `json:"ciArtifactLocation"` // s3 bucket+ path
CiArtifactBucket string `json:"ciArtifactBucket"`
CiArtifactFileName string `json:"ciArtifactFileName"`
CiArtifactRegion string `json:"ciArtifactRegion"`
BlobStorageS3Config *blobStorage.BlobStorageS3Config `json:"blobStorageS3Config"`
CiCacheRegion string `json:"ciCacheRegion"`
CiCacheFileName string `json:"ciCacheFileName"`
PipelineId int `json:"pipelineId"`
PipelineName string `json:"pipelineName"`
WorkflowId int `json:"workflowId"`
TriggeredBy int `json:"triggeredBy"`
CacheLimit int64 `json:"cacheLimit"`
BeforeDockerBuild []*Task `json:"beforeDockerBuildScripts"`
AfterDockerBuild []*Task `json:"afterDockerBuildScripts"`
CiYamlLocation string `json:"CiYamlLocations"`
TaskYaml *TaskYaml `json:"-"`
TestExecutorImageProperties *TestExecutorImageProperties `json:"testExecutorImageProperties"`
BlobStorageConfigured bool `json:"blobStorageConfigured"`
IgnoreDockerCachePull bool `json:"ignoreDockerCachePull"`
IgnoreDockerCachePush bool `json:"ignoreDockerCachePush"`
ScanEnabled bool `json:"scanEnabled"`
CloudProvider blobStorage.BlobStorageType `json:"cloudProvider"`
AzureBlobConfig *blobStorage.AzureBlobConfig `json:"azureBlobConfig"`
GcpBlobConfig *blobStorage.GcpBlobConfig `json:"gcpBlobConfig"`
BlobStorageLogsKey string `json:"blobStorageLogsKey"`
InAppLoggingEnabled bool `json:"inAppLoggingEnabled"`
MinioEndpoint string `json:"minioEndpoint"`
DefaultAddressPoolBaseCidr string `json:"defaultAddressPoolBaseCidr"`
DefaultAddressPoolSize int `json:"defaultAddressPoolSize"`
PreCiSteps []*StepObject `json:"preCiSteps"`
PostCiSteps []*StepObject `json:"postCiSteps"`
RefPlugins []*RefPluginObject `json:"refPlugins"`
AppName string `json:"appName"`
TriggerByAuthor string `json:"triggerByAuthor"`
CiBuildConfig *CiBuildConfigBean `json:"ciBuildConfig"`
CiBuildDockerMtuValue int `json:"ciBuildDockerMtuValue"`
CacheInvalidate bool `json:"cacheInvalidate"`
IsPvcMounted bool `json:"IsPvcMounted"`
ExtraEnvironmentVariables map[string]string `json:"extraEnvironmentVariables"`
EnableBuildContext bool `json:"enableBuildContext"`
IsExtRun bool `json:"isExtRun"`
OrchestratorHost string `json:"orchestratorHost"`
OrchestratorToken string `json:"orchestratorToken"`
ImageRetryCount int `json:"imageRetryCount"`
ImageRetryInterval int `json:"imageRetryInterval"`
EnableSecretMasking bool `json:"enableSecretMasking"`
}
type CdRequest struct {
WorkflowId int `json:"workflowId"`
WorkflowRunnerId int `json:"workflowRunnerId"`
CdPipelineId int `json:"cdPipelineId"`
TriggeredBy int32 `json:"triggeredBy"`
StageYaml string `json:"stageYaml"`
ArtifactLocation string `json:"artifactLocation"`
ArtifactBucket string `json:"ciArtifactBucket"`
ArtifactFileName string `json:"ciArtifactFileName"`
ArtifactRegion string `json:"ciArtifactRegion"`
BlobStorageS3Config *blobStorage.BlobStorageS3Config `json:"blobStorageS3Config"`
TaskYaml *TaskYaml `json:"-"`
CiProjectDetails []CiProjectDetails `json:"ciProjectDetails"`
CiArtifactDTO CiArtifactDTO `json:"ciArtifactDTO"`
DockerUsername string `json:"dockerUsername"`
DockerPassword string `json:"dockerPassword"`
AwsRegion string `json:"awsRegion"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
DockerRegistryURL string `json:"dockerRegistryUrl"`
DockerRegistryType string `json:"dockerRegistryType"`
DockerConnection string `json:"dockerConnection"`
DockerCert string `json:"dockerCert"`
OrchestratorHost string `json:"orchestratorHost"`
OrchestratorToken string `json:"orchestratorToken"`
IsExtRun bool `json:"isExtRun"`
ExtraEnvironmentVariables map[string]string `json:"extraEnvironmentVariables"`
CloudProvider blobStorage.BlobStorageType `json:"cloudProvider"`
BlobStorageConfigured bool `json:"blobStorageConfigured"`
AzureBlobConfig *blobStorage.AzureBlobConfig `json:"azureBlobConfig"`
GcpBlobConfig *blobStorage.GcpBlobConfig `json:"gcpBlobConfig"`
BlobStorageLogsKey string `json:"blobStorageLogsKey"`
InAppLoggingEnabled bool `json:"inAppLoggingEnabled"`
MinioEndpoint string `json:"minioEndpoint"`
DefaultAddressPoolBaseCidr string `json:"defaultAddressPoolBaseCidr"`
DefaultAddressPoolSize int `json:"defaultAddressPoolSize"`
DeploymentTriggeredBy string `json:"deploymentTriggeredBy"`
DeploymentTriggerTime time.Time `json:"deploymentTriggerTime"`
CiRunnerDockerMtuValue int `json:"ciRunnerDockerMtuValue"`
DeploymentReleaseCounter int `json:"deploymentReleaseCounter,omitempty"`
IsDryRun bool `json:"isDryRun"`
PrePostDeploySteps []*StepObject `json:"prePostDeploySteps"`
RefPlugins []*RefPluginObject `json:"refPlugins"`
StageType string `json:"stageType"`
}
type CiCdTriggerEvent struct {
Type string `json:"type"`
CommonWorkflowRequest *CommonWorkflowRequest `json:"commonWorkflowRequest"`
}
type ExtEnvRequest struct {
OrchestratorHost string `json:"orchestratorHost"`
OrchestratorToken string `json:"orchestratorToken"`
IsExtRun bool `json:"isExtRun"`
}
type CiArtifactDTO struct {
Id int `json:"id"`
PipelineId int `json:"pipelineId"` //id of the ci pipeline from which this webhook was triggered
Image string `json:"image"`
ImageDigest string `json:"imageDigest"`
MaterialInfo string `json:"materialInfo"` //git material metadata json array string
DataSource string `json:"dataSource"`
WorkflowId *int `json:"workflowId"`
}
type CiCompleteEvent struct {
CiProjectDetails []CiProjectDetails `json:"ciProjectDetails"`
DockerImage string `json:"dockerImage"`
Digest string `json:"digest"`
PipelineId int `json:"pipelineId"`
DataSource string `json:"dataSource"`
PipelineName string `json:"pipelineName"`
WorkflowId int `json:"workflowId"`
TriggeredBy int `json:"triggeredBy"`
MaterialType string `json:"materialType"`
Metrics CIMetrics `json:"metrics"`
AppName string `json:"appName"`
IsArtifactUploaded bool `json:"isArtifactUploaded"`
FailureReason string `json:"failureReason"` // FailureReason is used for notifying the failure reason to the user. Should be short and user-friendly
ImageDetailsFromCR json.RawMessage `json:"imageDetailsFromCR"`
PluginRegistryArtifactDetails map[string][]string `json:"PluginRegistryArtifactDetails"`
PluginArtifactStage string `json:"pluginArtifactStage"`
IsScanEnabled bool `json:"isScanEnabled"`
PluginArtifacts *PluginArtifacts `json:"pluginArtifacts"`
DockerRegistryId string `json:"dockerRegistryId"`
}
func (event *CiCompleteEvent) WithMetrics(metrics CIMetrics) *CiCompleteEvent {
event.Metrics = metrics
return event
}
func (event *CiCompleteEvent) WithFailureReason(failureReason string) *CiCompleteEvent {
event.FailureReason = failureReason
return event
}
func (event *CiCompleteEvent) WithImageDetailsFromCR(imageDetailsFromCR json.RawMessage) *CiCompleteEvent {
event.ImageDetailsFromCR = imageDetailsFromCR
return event
}
func (event *CiCompleteEvent) WithPluginArtifacts(pluginArtifacts *PluginArtifacts) *CiCompleteEvent {
event.PluginArtifacts = pluginArtifacts
return event
}
func (event *CiCompleteEvent) WithDockerImage(dockerImage string) *CiCompleteEvent {
event.DockerImage = dockerImage
return event
}
func (event *CiCompleteEvent) WithDigest(digest string) *CiCompleteEvent {
event.Digest = digest
return event
}
func (event *CiCompleteEvent) WithIsArtifactUploaded(artifactUploaded bool) *CiCompleteEvent {
event.IsArtifactUploaded = artifactUploaded
return event
}
type StageFailureEvent struct {
WorkflowId int `json:"workflowId"`
WorkflowType PipelineType `json:"workflowType"`
IsArtifactUploaded bool `json:"isArtifactUploaded"`
FailureReason error `json:"failureReason"`
}
type PipelineType string
const (
CI PipelineType = "CI"
PRE_CD PipelineType = "PRE-CD"
POST_CD PipelineType = "POST-CD"
)
type ImageScanningEvent struct {
CiPipelineId int `json:"ciPipelineId"`
CdPipelineId int `json:"cdPipelineId"`
TriggerBy int `json:"triggeredBy"`
Image string `json:"image"`
Digest string `json:"digest"`
PipelineType PipelineType `json:"PipelineType"`
}
type CdStageCompleteEvent struct {
CiProjectDetails []CiProjectDetails `json:"ciProjectDetails"`
WorkflowId int `json:"workflowId"`
WorkflowRunnerId int `json:"workflowRunnerId"`
CdPipelineId int `json:"cdPipelineId"`
TriggeredBy int `json:"triggeredBy"`
StageYaml string `json:"stageYaml"`
ArtifactLocation string `json:"artifactLocation"`
TaskYaml *TaskYaml `json:"-"`
PipelineName string `json:"pipelineName"`
CiArtifactDTO CiArtifactDTO `json:"ciArtifactDTO"`
PluginRegistryArtifactDetails map[string][]string `json:"PluginRegistryArtifactDetails"`
PluginArtifactStage string `json:"pluginArtifactStage"`
PluginArtifacts *PluginArtifacts `json:"pluginArtifacts"`
IsArtifactUploaded bool `json:"isArtifactUploaded"`
}
func (event *CdStageCompleteEvent) WithPluginArtifacts(pluginArtifacts *PluginArtifacts) *CdStageCompleteEvent {
event.PluginArtifacts = pluginArtifacts
return event
}
func (event *CdStageCompleteEvent) WithIsArtifactUploaded(artifactUploaded bool) *CdStageCompleteEvent {
event.IsArtifactUploaded = artifactUploaded
return event
}
type CiProjectDetails struct {
GitRepository string `json:"gitRepository"`
FetchSubmodules bool `json:"fetchSubmodules"`
MaterialName string `json:"materialName"`
CheckoutPath string `json:"checkoutPath"`
CommitHash string `json:"commitHash"`
GitTag string `json:"gitTag"`
CommitTime time.Time `json:"commitTime"`
SourceType SourceType `json:"sourceType"`
SourceValue string `json:"sourceValue"`
Type string `json:"type"`
Message string `json:"message"`
Author string `json:"author"`
GitOptions GitOptions `json:"gitOptions"`
WebhookData WebhookData `json:"webhookData"`
CloningMode string `json:"cloningMode"`
}
type RegistryCredentials struct {
RegistryType string `json:"registryType"`
RegistryURL string `json:"registryURL"`
Username string `json:"username"`
Password string `json:"password"`
AWSAccessKeyId string `json:"awsAccessKeyId,omitempty"`
AWSSecretAccessKey string `json:"awsSecretAccessKey,omitempty"`
AWSRegion string `json:"awsRegion,omitempty"`
}
type PublishRequest struct {
Topic string `json:"topic"`
Payload json.RawMessage `json:"payload"`
}
type CIMetrics struct {
CacheDownDuration float64 `json:"cacheDownDuration"`
PreCiDuration float64 `json:"preCiDuration"`
BuildDuration float64 `json:"buildDuration"`
PostCiDuration float64 `json:"postCiDuration"`
CacheUpDuration float64 `json:"cacheUpDuration"`
TotalDuration float64 `json:"totalDuration"`
CacheDownStartTime time.Time `json:"cacheDownStartTime"`
PreCiStartTime time.Time `json:"preCiStart"`
BuildStartTime time.Time `json:"buildStartTime"`
PostCiStartTime time.Time `json:"postCiStartTime"`
CacheUpStartTime time.Time `json:"cacheUpStartTime"`
TotalStartTime time.Time `json:"totalStartTime"`
}
type CiProjectDetailsMin struct {
CommitHash string `json:"commitHash"`
Message string `json:"message"`
Author string `json:"author"`
CommitTime time.Time `json:"commitTime"`
}
func SendCDEvent(cdRequest *CommonWorkflowRequest, event *CdStageCompleteEvent) error {
err := sendCdCompleteEvent(cdRequest, event)
if err != nil {
log.Println(util.DEVTRON, "err", err)
return err
}
return nil
}
func SendCiCompleteEvent(ciRequest *CommonWorkflowRequest, event *CiCompleteEvent) error {
if event == nil {
log.Println(util.DEVTRON, "err", "empty event received")
return nil
}
err := sendCiCompleteEvent(ciRequest, event)
if err != nil {
log.Println(util.DEVTRON, "err", err)
return err
}
log.Println(util.DEVTRON, " housekeeping done. exiting now")
return nil
}
func sendCiCompleteEvent(ciRequest *CommonWorkflowRequest, event *CiCompleteEvent) error {
jsonBody, err := json.Marshal(event)
if err != nil {
log.Println(util.DEVTRON, "err", err)
return err
}
extEnvRequest := GetExternalEnvRequest(*ciRequest)
err = PublishEvent(jsonBody, pubSub.CI_COMPLETE_TOPIC, &extEnvRequest)
log.Println(util.DEVTRON, "ci complete event notification done")
return err
}
func sendCdCompleteEvent(cdRequest *CommonWorkflowRequest, event *CdStageCompleteEvent) error {
jsonBody, err := json.Marshal(event)
if err != nil {
log.Println(util.DEVTRON, "err", err)
return err
}
extEnvRequest := GetExternalEnvRequest(*cdRequest)
err = PublishCDEvent(jsonBody, pubSub.CD_STAGE_COMPLETE_TOPIC, &extEnvRequest)
log.Println(util.DEVTRON, "cd stage complete event notification done")
return err
}
func PublishCDEvent(jsonBody []byte, topic string, cdRequest *ExtEnvRequest) error {
if cdRequest.IsExtRun {
return PublishEventsOnRest(jsonBody, topic, cdRequest)
}
return pubsub.PublishEventsOnNats(jsonBody, topic)
}
func PublishEvent(jsonBody []byte, topic string, ciRequest *ExtEnvRequest) error {
if ciRequest.IsExtRun {
return PublishEventsOnRest(jsonBody, topic, ciRequest)
}
return pubsub.PublishEventsOnNats(jsonBody, topic)
}
func PublishEventsOnRest(jsonBody []byte, topic string, cdRequest *ExtEnvRequest) error {
publishRequest := &PublishRequest{
Topic: topic,
Payload: jsonBody,
}
client := resty.New()
client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
resp, err := client.SetRetryCount(4).R().
SetHeader("Content-Type", "application/json").
SetBody(publishRequest).
SetAuthToken(cdRequest.OrchestratorToken).
//SetResult(). // or SetResult(AuthSuccess{}).
Post(cdRequest.OrchestratorHost)
if err != nil {
log.Println(util.DEVTRON, "err in publishing over rest", err)
return err
}
log.Println(util.DEVTRON, "res ", string(resp.Body()))
return nil
}
func ExecuteImageScanningViaRest(event *ScanEvent) error {
jsonBody, err := json.Marshal(event)
if err != nil {
log.Println(util.DEVTRON, "err", err)
return err
}
cfg := &pubsub.PubSubConfig{}
err = env.Parse(cfg)
if err != nil {
return err
}
client := resty.New()
client.
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
SetRetryCount(event.ImageScanMaxRetries).SetRetryMaxWaitTime(time.Duration(event.ImageScanRetryDelay)).
AddRetryCondition(
func(r *resty.Response, err error) bool {
return err != nil || r.StatusCode() != http.StatusOK
},
).AddRetryHook(
func(r *resty.Response, err error) {
println(fmt.Sprintf("IMAGE SCAN failed with status code = %v. RETRYING...", r.StatusCode()))
})
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(jsonBody).
Post(fmt.Sprintf("%s/%s", cfg.ImageScannerEndpoint, "scanner/image"))
if err != nil {
log.Println(util.DEVTRON, "err in image scanner app over rest", err)
return err
}
if resp.StatusCode() != 200 {
log.Println(fmt.Sprintf("======== Vulnerability Scanning request failed with HTTP status code %v ========", resp.StatusCode()))
return fmt.Errorf("%s", string(resp.Body()))
}
log.Println(util.DEVTRON, resp.StatusCode())
log.Println(util.DEVTRON, resp)
return nil
}
type ScanEvent struct {
bean2.ImageScanEvent
ImageScanMaxRetries int `json:"imageScanMaxRetries,omitempty"`
ImageScanRetryDelay int `json:"imageScanRetryDelay,omitempty"`
}
func (dockerBuildConfig *DockerBuildConfig) GetProvenanceFlag() string {
// if provenance mode is provided, set provenance, else set to false
if dockerBuildConfig.BuildxProvenanceMode != "" {
return fmt.Sprintf("--provenance=mode=%s ", dockerBuildConfig.BuildxProvenanceMode)
}
// --provinance is set to true by default by docker. this will add some build related data in generated build manifest.it also adds some
// unknown:unknown key:value pair which may not be compatible by some container registries.
// with buildx k8s driver , --provinenance=true is causing issue when push manifest to quay registry, so setting it to false
// above issue is being tracked in https://github.com/moby/buildkit/issues/3222
return "--provenance=false"
}
func (dockerBuildConfig *DockerBuildConfig) CheckForBuildX() bool {
return dockerBuildConfig.TargetPlatform != "" || dockerBuildConfig.UseBuildx
}
func (dockerBuildConfig *DockerBuildConfig) CheckForBuildXK8sDriver() (bool, []map[string]string) {
buildxEnabled := dockerBuildConfig.CheckForBuildX()
eligibleK8sNodes := dockerBuildConfig.GetEligibleK8sDriverNodes()
useBuildxK8sDriver := buildxEnabled && len(eligibleK8sNodes) > 0
return useBuildxK8sDriver, eligibleK8sNodes
}
func (dockerBuildConfig *DockerBuildConfig) GetEligibleK8sDriverNodes() []map[string]string {
if dockerBuildConfig.TargetPlatform == "" {
return findDefaultBuildxNodes(dockerBuildConfig.BuildxK8sDriverOptions)
}
return filterBuilderNodes(dockerBuildConfig.BuildxK8sDriverOptions, dockerBuildConfig.TargetPlatform)
}
func filterBuilderNodes(builderNodes []map[string]string, targetPlatformStr string) []map[string]string {
filteredBuilderNodes := make([]map[string]string, 0)
requiredTargetPlatformSet := make(map[string]bool) //user requested platforms for build
canBeBuildTargetPlatformSet := make(map[string]bool) //platforms that can be built with provided k8s Driver Nodes
for _, platform := range strings.Split(targetPlatformStr, ",") {
requiredTargetPlatformSet[platform] = true
}
for _, builderNode := range builderNodes {
platformStr := builderNode["platform"]
for _, platform := range strings.Split(platformStr, ",") {
if requiredTargetPlatformSet[platform] {
canBeBuildTargetPlatformSet[platform] = true
filteredBuilderNodes = append(filteredBuilderNodes, builderNode) //filtering out required k8s Driver nodes only
}
}
}
if len(requiredTargetPlatformSet) != len(canBeBuildTargetPlatformSet) {
fmt.Println(util.DEVTRON, " Docker k8s driver nodes required to build for these platforms ", targetPlatformStr, " are not present, so not using docker k8s driver for this build ")
return nil
}
return filteredBuilderNodes
}
func findDefaultBuildxNodes(builderNodes []map[string]string) []map[string]string {
defaultNodes := make([]map[string]string, 0)
for _, builderNode := range builderNodes {
if isDefault, _ := builderNode[util.DEFAULT_KEY]; isDefault == "true" {
defaultNodes = append(defaultNodes, builderNode)
break
}
}
return builderNodes
}
func (prj *CiProjectDetails) GetCheckoutBranchName() string {
var checkoutBranch string
if prj.SourceType == SOURCE_TYPE_WEBHOOK {
webhookData := prj.WebhookData
webhookDataData := webhookData.Data
checkoutBranch = webhookDataData[WEBHOOK_SELECTOR_TARGET_CHECKOUT_BRANCH_NAME]
if len(checkoutBranch) == 0 {
//webhook type is tag based
checkoutBranch = webhookDataData[WEBHOOK_SELECTOR_TARGET_CHECKOUT_NAME]
}
} else {
if len(prj.SourceValue) == 0 {
checkoutBranch = "main"
} else {
checkoutBranch = prj.SourceValue
}
}
if len(checkoutBranch) == 0 {
log.Fatal("could not get target checkout from request data")
}
return checkoutBranch
}
func GetExternalEnvRequest(ciCdRequest CommonWorkflowRequest) ExtEnvRequest {
extEnvRequest := ExtEnvRequest{
OrchestratorHost: ciCdRequest.OrchestratorHost,
OrchestratorToken: ciCdRequest.OrchestratorToken,
IsExtRun: ciCdRequest.IsExtRun,
}
return extEnvRequest
}
func GetImageScanningEvent(ciCdRequest CommonWorkflowRequest) ImageScanningEvent {
event := ImageScanningEvent{
CiPipelineId: ciCdRequest.PipelineId,
CdPipelineId: ciCdRequest.CdPipelineId,
TriggerBy: ciCdRequest.TriggeredBy,
Image: ciCdRequest.CiArtifactDTO.Image,
Digest: ciCdRequest.CiArtifactDTO.ImageDigest,
}
var stage PipelineType
if ciCdRequest.StageType == string(STEP_TYPE_PRE) {
stage = PRE_CD
} else if ciCdRequest.StageType == string(STEP_TYPE_POST) {
stage = POST_CD
}
event.PipelineType = stage
return event
}
type ImageScanningSteps struct {
Steps []*StepObject `json:"steps"`
ScanToolId int `json:"scanToolId"`
}