-
Notifications
You must be signed in to change notification settings - Fork 563
/
Copy pathgithub.go
1544 lines (1361 loc) · 59.4 KB
/
github.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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 controllers
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/diggerhq/digger/backend/ci_backends"
config2 "github.com/diggerhq/digger/backend/config"
"github.com/diggerhq/digger/backend/locking"
"github.com/diggerhq/digger/backend/middleware"
"github.com/diggerhq/digger/backend/models"
"github.com/diggerhq/digger/backend/segment"
"github.com/diggerhq/digger/backend/services"
"github.com/diggerhq/digger/backend/utils"
"github.com/diggerhq/digger/libs/ci"
"github.com/diggerhq/digger/libs/ci/generic"
dg_github "github.com/diggerhq/digger/libs/ci/github"
comment_updater "github.com/diggerhq/digger/libs/comment_utils/reporting"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
dg_locking "github.com/diggerhq/digger/libs/locking"
orchestrator_scheduler "github.com/diggerhq/digger/libs/scheduler"
"github.com/dominikbraun/graph"
"github.com/gin-gonic/gin"
"github.com/google/go-github/v61/github"
"github.com/google/uuid"
"github.com/samber/lo"
"golang.org/x/oauth2"
"gorm.io/gorm"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime/debug"
"slices"
"strconv"
"strings"
)
type IssueCommentHook func(gh utils.GithubClientProvider, payload *github.IssueCommentEvent, ciBackendProvider ci_backends.CiBackendProvider) error
type DiggerController struct {
CiBackendProvider ci_backends.CiBackendProvider
GithubClientProvider utils.GithubClientProvider
GithubWebhookPostIssueCommentHooks []IssueCommentHook
}
func (d DiggerController) GithubAppWebHook(c *gin.Context) {
c.Header("Content-Type", "application/json")
gh := d.GithubClientProvider
log.Printf("GithubAppWebHook")
appID := c.GetHeader("X-GitHub-Hook-Installation-Target-ID")
_, _, webhookSecret, _, err := d.GithubClientProvider.FetchCredentials(appID)
payload, err := github.ValidatePayload(c.Request, []byte(webhookSecret))
if err != nil {
log.Printf("Error validating github app webhook's payload: %v", err)
c.String(http.StatusBadRequest, "Error validating github app webhook's payload")
return
}
webhookType := github.WebHookType(c.Request)
event, err := github.ParseWebHook(webhookType, payload)
if err != nil {
log.Printf("Failed to parse Github Event. :%v\n", err)
c.String(http.StatusInternalServerError, "Failed to parse Github Event")
return
}
log.Printf("github event type: %v\n", reflect.TypeOf(event))
appId64, err := strconv.ParseInt(appID, 10, 64)
if err != nil {
log.Printf("Error converting appId string to int64: %v", err)
return
}
switch event := event.(type) {
case *github.InstallationEvent:
log.Printf("InstallationEvent, action: %v\n", *event.Action)
if *event.Action == "deleted" {
err := handleInstallationDeletedEvent(event, appId64)
if err != nil {
c.String(http.StatusAccepted, "Failed to handle webhook event.")
return
}
}
case *github.IssueCommentEvent:
log.Printf("IssueCommentEvent, action: %v\n", *event.Action)
if event.Sender.Type != nil && *event.Sender.Type == "Bot" {
c.String(http.StatusOK, "OK")
return
}
go handleIssueCommentEvent(gh, event, d.CiBackendProvider, appId64, d.GithubWebhookPostIssueCommentHooks)
case *github.PullRequestEvent:
log.Printf("Got pull request event for %d", *event.PullRequest.ID)
// run it as a goroutine to avoid timeouts
go handlePullRequestEvent(gh, event, d.CiBackendProvider, appId64)
default:
log.Printf("Unhandled event, event type %v", reflect.TypeOf(event))
}
c.JSON(http.StatusAccepted, "ok")
}
func GithubAppSetup(c *gin.Context) {
type githubWebhook struct {
URL string `json:"url"`
Active bool `json:"active"`
}
type githubAppRequest struct {
Description string `json:"description"`
Events []string `json:"default_events"`
Name string `json:"name"`
Permissions map[string]string `json:"default_permissions"`
Public bool `json:"public"`
RedirectURL string `json:"redirect_url"`
CallbackUrls []string `json:"callback_urls"`
RequestOauthOnInstall bool `json:"request_oauth_on_install"`
SetupOnUpdate bool `json:"setup_on_update"`
URL string `json:"url"`
Webhook *githubWebhook `json:"hook_attributes"`
}
host := os.Getenv("HOSTNAME")
manifest := &githubAppRequest{
Name: fmt.Sprintf("Digger app %v", rand.Int31()),
Description: fmt.Sprintf("Digger hosted at %s", host),
URL: host,
RedirectURL: fmt.Sprintf("%s/github/exchange-code", host),
Public: false,
Webhook: &githubWebhook{
Active: true,
URL: fmt.Sprintf("%s/github-app-webhook", host),
},
CallbackUrls: []string{fmt.Sprintf("%s/github/callback", host)},
SetupOnUpdate: true,
RequestOauthOnInstall: true,
Events: []string{
"check_run",
"create",
"delete",
"issue_comment",
"issues",
"status",
"pull_request_review_thread",
"pull_request_review_comment",
"pull_request_review",
"pull_request",
"push",
},
Permissions: map[string]string{
"actions": "write",
"contents": "write",
"issues": "write",
"pull_requests": "write",
"repository_hooks": "write",
"statuses": "write",
"administration": "read",
"checks": "write",
"members": "read",
"workflows": "write",
},
}
githubHostname := utils.GetGithubHostname()
url := &url.URL{
Scheme: "https",
Host: githubHostname,
Path: "/settings/apps/new",
}
// https://developer.github.com/apps/building-github-apps/creating-github-apps-using-url-parameters/#about-github-app-url-parameters
githubOrg := os.Getenv("GITHUB_ORG")
if githubOrg != "" {
url.Path = fmt.Sprintf("organizations/%s%s", githubOrg, url.Path)
}
jsonManifest, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
c.Error(fmt.Errorf("failed to serialize manifest %s", err))
return
}
c.HTML(http.StatusOK, "github_setup.tmpl", gin.H{"Target": url.String(), "Manifest": string(jsonManifest)})
}
// GithubSetupExchangeCode handles the user coming back from creating their app
// A code query parameter is exchanged for this app's ID, key, and webhook_secret
// Implements https://developer.github.com/apps/building-github-apps/creating-github-apps-from-a-manifest/#implementing-the-github-app-manifest-flow
func (d DiggerController) GithubSetupExchangeCode(c *gin.Context) {
code := c.Query("code")
if code == "" {
c.Error(fmt.Errorf("Ignoring callback, missing code query parameter"))
}
// TODO: to make tls verification configurable for debug purposes
//var transport *http.Transport = nil
//_, exists := os.LookupEnv("DIGGER_GITHUB_SKIP_TLS")
//if exists {
// transport = &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
// }
//}
client, err := d.GithubClientProvider.NewClient(nil)
if err != nil {
c.Error(fmt.Errorf("could not create github client: %v", err))
}
cfg, _, err := client.Apps.CompleteAppManifest(context.Background(), code)
if err != nil {
c.Error(fmt.Errorf("Failed to exchange code for github app: %s", err))
return
}
log.Printf("Found credentials for GitHub app %v with id %d", *cfg.Name, cfg.GetID())
PEM := cfg.GetPEM()
PemBase64 := base64.StdEncoding.EncodeToString([]byte(PEM))
c.HTML(http.StatusOK, "github_setup.tmpl", gin.H{
"Target": "",
"Manifest": "",
"ID": cfg.GetID(),
"ClientID": cfg.GetClientID(),
"ClientSecret": cfg.GetClientSecret(),
"Key": PEM,
"KeyBase64": PemBase64,
"WebhookSecret": cfg.GetWebhookSecret(),
"URL": cfg.GetHTMLURL(),
})
}
func createOrGetDiggerRepoForGithubRepo(ghRepoFullName string, ghRepoOrganisation string, ghRepoName string, ghRepoUrl string, installationId int64) (*models.Repo, *models.Organisation, error) {
link, err := models.DB.GetGithubInstallationLinkForInstallationId(installationId)
if err != nil {
log.Printf("Error fetching installation link: %v", err)
return nil, nil, err
}
orgId := link.OrganisationId
org, err := models.DB.GetOrganisationById(orgId)
if err != nil {
log.Printf("Error fetching organisation by id: %v, error: %v\n", orgId, err)
return nil, nil, err
}
diggerRepoName := strings.ReplaceAll(ghRepoFullName, "/", "-")
// using Unscoped because we also need to include deleted repos (and undelete them if they exist)
var existingRepo models.Repo
r := models.DB.GormDB.Unscoped().Where("organisation_id=? AND repos.name=?", orgId, diggerRepoName).Find(&existingRepo)
if r.Error != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("repo not found, will proceed with repo creation")
} else {
log.Printf("Error fetching repo: %v", err)
return nil, nil, err
}
}
if r.RowsAffected > 0 {
existingRepo.DeletedAt = gorm.DeletedAt{}
models.DB.GormDB.Save(&existingRepo)
log.Printf("Digger repo already exists: %v", existingRepo)
return &existingRepo, org, nil
}
repo, err := models.DB.CreateRepo(diggerRepoName, ghRepoFullName, ghRepoOrganisation, ghRepoName, ghRepoUrl, org, `
generate_projects:
include: "."
`)
if err != nil {
log.Printf("Error creating digger repo: %v", err)
return nil, nil, err
}
log.Printf("Created digger repo: %v", repo)
return repo, org, nil
}
func handleInstallationDeletedEvent(installation *github.InstallationEvent, appId int64) error {
installationId := *installation.Installation.ID
link, err := models.DB.GetGithubInstallationLinkForInstallationId(installationId)
if err != nil {
return err
}
_, err = models.DB.MakeGithubAppInstallationLinkInactive(link)
if err != nil {
return err
}
for _, repo := range installation.Repositories {
repoFullName := *repo.FullName
log.Printf("Removing an installation %d for repo: %s", installationId, repoFullName)
_, err := models.DB.GithubRepoRemoved(installationId, appId, repoFullName)
if err != nil {
return err
}
}
return nil
}
func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullRequestEvent, ciBackendProvider ci_backends.CiBackendProvider, appId int64) error {
defer func() {
if r := recover(); r != nil {
log.Printf("Recovered from panic in handlePullRequestEvent handler: %v", r)
log.Printf("\n=== PANIC RECOVERED ===\n")
log.Printf("Error: %v\n", r)
log.Printf("Stack Trace:\n%s", string(debug.Stack()))
log.Printf("=== END PANIC ===\n")
}
}()
installationId := *payload.Installation.ID
repoName := *payload.Repo.Name
repoOwner := *payload.Repo.Owner.Login
repoFullName := *payload.Repo.FullName
cloneURL := *payload.Repo.CloneURL
prNumber := *payload.PullRequest.Number
isDraft := payload.PullRequest.GetDraft()
commitSha := payload.PullRequest.Head.GetSHA()
branch := payload.PullRequest.Head.GetRef()
action := *payload.Action
labels := payload.PullRequest.Labels
prLabelsStr := lo.Map(labels, func(label *github.Label, i int) string {
return *label.Name
})
link, err := models.DB.GetGithubAppInstallationLink(installationId)
if err != nil {
log.Printf("Error getting GetGithubAppInstallationLink: %v", err)
return fmt.Errorf("error getting github app link")
}
organisationId := link.OrganisationId
ghService, _, ghServiceErr := utils.GetGithubService(gh, installationId, repoFullName, repoOwner, repoName)
if ghServiceErr != nil {
log.Printf("GetGithubService error: %v", err)
return fmt.Errorf("error getting ghService to post error comment")
}
// here we check if pr was closed and automatic deletion is enabled, to avoid errors when
// pr is merged and the branch does not exist we handle that gracefully
if action == "closed" {
branchName, _, err := ghService.GetBranchName(prNumber)
if err != nil {
utils.InitCommentReporter(ghService, prNumber, fmt.Sprintf(":x: Could not retrieve PR details, error: %v", err))
log.Printf("Could not retrieve PR details error: %v", err)
return fmt.Errorf("Could not retrieve PR details: %v", err)
}
branchExists, err := ghService.CheckBranchExists(branchName)
if err != nil {
utils.InitCommentReporter(ghService, prNumber, fmt.Sprintf(":x: Could not check if branch exists, error: %v", err))
log.Printf("Could not check if branch exists, error: %v", err)
return fmt.Errorf("Could not check if branch exists: %v", err)
}
if !branchExists {
log.Printf("automating branch deletion is configured, ignoring pr closed event")
return nil
}
}
if !slices.Contains([]string{"closed", "opened", "reopened", "synchronize", "converted_to_draft"}, action) {
log.Printf("The action %v is not one that we should act on, ignoring webhook event", action)
return nil
}
commentReporterManager := utils.InitCommentReporterManager(ghService, prNumber)
if _, exists := os.LookupEnv("DIGGER_REPORT_BEFORE_LOADING_CONFIG"); exists {
_, err := commentReporterManager.UpdateComment(":construction_worker: Digger starting....")
if err != nil {
log.Printf("Error initializing comment reporter: %v", err)
return fmt.Errorf("error initializing comment reporter")
}
}
diggerYmlStr, ghService, config, projectsGraph, _, _, changedFiles, err := getDiggerConfigForPR(gh, organisationId, prLabelsStr, installationId, repoFullName, repoOwner, repoName, cloneURL, prNumber)
if err != nil {
log.Printf("getDiggerConfigForPR error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error loading digger config: %v", err))
return fmt.Errorf("error getting digger config")
}
impactedProjects, impactedProjectsSourceMapping, _, err := dg_github.ProcessGitHubPullRequestEvent(payload, config, projectsGraph, ghService)
if err != nil {
log.Printf("Error processing event: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error processing event: %v", err))
return fmt.Errorf("error processing event")
}
jobsForImpactedProjects, _, err := dg_github.ConvertGithubPullRequestEventToJobs(payload, impactedProjects, nil, *config, false)
if err != nil {
log.Printf("Error converting event to jobsForImpactedProjects: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error converting event to jobsForImpactedProjects: %v", err))
return fmt.Errorf("error converting event to jobsForImpactedProjects")
}
if len(jobsForImpactedProjects) == 0 {
// do not report if no projects are impacted to minimise noise in the PR thread
// TODO use status checks instead: https://github.com/diggerhq/digger/issues/1135
log.Printf("No projects impacted; not starting any jobs")
// This one is for aggregate reporting
err = utils.SetPRStatusForJobs(ghService, prNumber, jobsForImpactedProjects)
return nil
}
// if flag set we dont allow more projects impacted than the number of changed files in PR (safety check)
if config2.LimitByNumOfFilesChanged() {
if len(impactedProjects) > len(changedFiles) {
log.Printf("Error the number impacted projects %v exceeds number of changed files: %v", len(impactedProjects), len(changedFiles))
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error the number impacted projects %v exceeds number of changed files: %v", len(impactedProjects), len(changedFiles)))
log.Printf("Information about the event:")
log.Printf("GH payload: %v", payload)
log.Printf("PR changed files: %v", changedFiles)
log.Printf("digger.yml STR: %v", diggerYmlStr)
log.Printf("Parsed config: %v", config)
log.Printf("Dependency graph:")
spew.Dump(projectsGraph)
log.Printf("Impacted Projects: %v", impactedProjects)
log.Printf("Impacted Project jobs: %v", jobsForImpactedProjects)
return fmt.Errorf("error processing event")
}
}
diggerCommand, err := orchestrator_scheduler.GetCommandFromJob(jobsForImpactedProjects[0])
if err != nil {
log.Printf("could not determine digger command from job: %v", jobsForImpactedProjects[0].Commands)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not determine digger command from job: %v", err))
return fmt.Errorf("unknown digger command in comment %v", err)
}
if *diggerCommand == orchestrator_scheduler.DiggerCommandNoop {
log.Printf("job is of type noop, no actions top perform")
return nil
}
// perform locking/unlocking in backend
if config.PrLocks {
for _, project := range impactedProjects {
prLock := dg_locking.PullRequestLock{
InternalLock: locking.BackendDBLock{
OrgId: organisationId,
},
CIService: ghService,
Reporter: comment_updater.NoopReporter{},
ProjectName: project.Name,
ProjectNamespace: repoFullName,
PrNumber: prNumber,
}
err = dg_locking.PerformLockingActionFromCommand(prLock, *diggerCommand)
if err != nil {
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Failed perform lock action on project: %v %v", project.Name, err))
return fmt.Errorf("failed to perform lock action on project: %v, %v", project.Name, err)
}
}
}
// if commands are locking or unlocking we don't need to trigger any jobs
if *diggerCommand == orchestrator_scheduler.DiggerCommandUnlock ||
*diggerCommand == orchestrator_scheduler.DiggerCommandLock {
commentReporterManager.UpdateComment(fmt.Sprintf(":white_check_mark: Command %v completed successfully", *diggerCommand))
return nil
}
if !config.AllowDraftPRs && isDraft {
log.Printf("Draft PRs are disabled, skipping PR: %v", prNumber)
return nil
}
commentReporter, err := commentReporterManager.UpdateComment(":construction_worker: Digger starting... Config loaded successfully")
if err != nil {
log.Printf("Error initializing comment reporter: %v", err)
return fmt.Errorf("error initializing comment reporter")
}
err = utils.ReportInitialJobsStatus(commentReporter, jobsForImpactedProjects)
if err != nil {
log.Printf("Failed to comment initial status for jobs: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Failed to comment initial status for jobs: %v", err))
return fmt.Errorf("failed to comment initial status for jobs")
}
err = utils.SetPRStatusForJobs(ghService, prNumber, jobsForImpactedProjects)
if err != nil {
log.Printf("error setting status for PR: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: error setting status for PR: %v", err))
fmt.Errorf("error setting status for PR: %v", err)
}
impactedProjectsMap := make(map[string]dg_configuration.Project)
for _, p := range impactedProjects {
impactedProjectsMap[p.Name] = p
}
impactedJobsMap := make(map[string]orchestrator_scheduler.Job)
for _, j := range jobsForImpactedProjects {
impactedJobsMap[j.ProjectName] = j
}
commentId, err := strconv.ParseInt(commentReporter.CommentId, 10, 64)
if err != nil {
log.Printf("strconv.ParseInt error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not handle commentId: %v", err))
}
var aiSummaryCommentId = ""
if config.Reporting.AiSummary {
aiSummaryComment, err := ghService.PublishComment(prNumber, "AI Summary will be posted here after completion")
if err != nil {
log.Printf("could not post ai summary comment: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
return fmt.Errorf("could not post ai summary comment: %v", err)
}
aiSummaryCommentId = aiSummaryComment.Id
}
batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, models.DiggerVCSGithub, organisationId, impactedJobsMap, impactedProjectsMap, projectsGraph, installationId, branch, prNumber, repoOwner, repoName, repoFullName, commitSha, commentId, diggerYmlStr, 0, aiSummaryCommentId, config.ReportTerraformOutputs)
if err != nil {
log.Printf("ConvertJobsToDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
return fmt.Errorf("error converting jobs")
}
if config.CommentRenderMode == dg_configuration.CommentRenderModeGroupByModule {
sourceDetails, err := comment_updater.PostInitialSourceComments(ghService, prNumber, impactedProjectsSourceMapping)
if err != nil {
log.Printf("PostInitialSourceComments error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: PostInitialSourceComments error: %v", err))
return fmt.Errorf("error posting initial comments")
}
batch, err := models.DB.GetDiggerBatch(batchId)
if err != nil {
log.Printf("GetDiggerBatch error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: PostInitialSourceComments error: %v", err))
return fmt.Errorf("error getting digger batch")
}
batch.SourceDetails, err = json.Marshal(sourceDetails)
if err != nil {
log.Printf("sourceDetails, json Marshal error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: json Marshal error: %v", err))
return fmt.Errorf("error marshalling sourceDetails")
}
err = models.DB.UpdateDiggerBatch(batch)
if err != nil {
log.Printf("UpdateDiggerBatch error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: UpdateDiggerBatch error: %v", err))
return fmt.Errorf("error updating digger batch")
}
}
segment.Track(strconv.Itoa(int(organisationId)), "backend_trigger_job")
ciBackend, err := ciBackendProvider.GetCiBackend(
ci_backends.CiBackendOptions{
GithubClientProvider: gh,
GithubInstallationId: installationId,
GithubAppId: appId,
RepoName: repoName,
RepoOwner: repoOwner,
RepoFullName: repoFullName,
},
)
if err != nil {
log.Printf("GetCiBackend error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: GetCiBackend error: %v", err))
return fmt.Errorf("error fetching ci backed %v", err)
}
err = TriggerDiggerJobs(ciBackend, repoFullName, repoOwner, repoName, batchId, prNumber, ghService, gh)
if err != nil {
log.Printf("TriggerDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: TriggerDiggerJobs error: %v", err))
return fmt.Errorf("error triggering Digger Jobs")
}
return nil
}
func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int64, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string, changedFiles []string) (string, *dg_github.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
ghService, token, err := utils.GetGithubService(gh, installationId, repoFullName, repoOwner, repoName)
if err != nil {
log.Printf("Error getting github service: %v", err)
return "", nil, nil, nil, fmt.Errorf("error getting github service")
}
var config *dg_configuration.DiggerConfig
var diggerYmlStr string
var dependencyGraph graph.Graph[string, dg_configuration.Project]
err = utils.CloneGitRepoAndDoAction(cloneUrl, branch, "", *token, "", func(dir string) error {
diggerYmlStr, err = dg_configuration.ReadDiggerYmlFileContents(dir)
if err != nil {
log.Printf("could not load digger config: %v", err)
return err
}
config, _, dependencyGraph, err = dg_configuration.LoadDiggerConfig(dir, true, changedFiles)
if err != nil {
log.Printf("Error loading digger config: %v", err)
return err
}
return nil
})
if err != nil {
log.Printf("Error cloning and loading config: %v", err)
return "", nil, nil, nil, fmt.Errorf("error cloning and loading config %v", err)
}
log.Printf("Digger config loadded successfully\n")
return diggerYmlStr, ghService, config, dependencyGraph, nil
}
// TODO: Refactor this func to receive ghService as input
func getDiggerConfigForPR(gh utils.GithubClientProvider, orgId uint, prLabels []string, installationId int64, repoFullName string, repoOwner string, repoName string, cloneUrl string, prNumber int) (string, *dg_github.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], *string, *string, []string, error) {
ghService, _, err := utils.GetGithubService(gh, installationId, repoFullName, repoOwner, repoName)
if err != nil {
log.Printf("Error getting github service: %v", err)
return "", nil, nil, nil, nil, nil, nil, fmt.Errorf("error getting github service")
}
var prBranch string
prBranch, prCommitSha, err := ghService.GetBranchName(prNumber)
if err != nil {
log.Printf("Error getting branch name: %v", err)
return "", nil, nil, nil, nil, nil, nil, fmt.Errorf("error getting branch name")
}
changedFiles, err := ghService.GetChangedFiles(prNumber)
if err != nil {
log.Printf("Error getting changed files: %v", err)
return "", nil, nil, nil, nil, nil, nil, fmt.Errorf("error getting changed files")
}
// check if items should be loaded from cache
if val, _ := os.LookupEnv("DIGGER_CONFIG_REPO_CACHE_ENABLED"); val == "1" && !slices.Contains(prLabels, "digger:no-cache") {
diggerYmlStr, config, dependencyGraph, err := retrieveConfigFromCache(orgId, repoFullName)
if err != nil {
log.Printf("could not load from cache")
} else {
log.Printf("successfully loaded from cache")
return diggerYmlStr, ghService, config, *dependencyGraph, &prBranch, &prCommitSha, changedFiles, nil
}
}
diggerYmlStr, ghService, config, dependencyGraph, err := GetDiggerConfigForBranch(gh, installationId, repoFullName, repoOwner, repoName, cloneUrl, prBranch, changedFiles)
if err != nil {
log.Printf("Error loading digger.yml: %v", err)
return "", nil, nil, nil, nil, nil, nil, fmt.Errorf("error loading digger.yml: %v", err)
}
return diggerYmlStr, ghService, config, dependencyGraph, &prBranch, &prCommitSha, changedFiles, nil
}
func retrieveConfigFromCache(orgId uint, repoFullName string) (string, *dg_configuration.DiggerConfig, *graph.Graph[string, dg_configuration.Project], error) {
repoCache, err := models.DB.GetRepoCache(orgId, repoFullName)
if err != nil {
log.Printf("Error: failed to load repoCache, going to try live load %v", err)
return "", nil, nil, fmt.Errorf("")
}
var config dg_configuration.DiggerConfig
err = json.Unmarshal(repoCache.DiggerConfig, &config)
if err != nil {
log.Printf("Error: failed to load repoCache unmarshall config %v", err)
return "", nil, nil, fmt.Errorf("failed to load repoCache unmarshall config %v", err)
}
projectsGraph, err := dg_configuration.CreateProjectDependencyGraph(config.Projects)
if err != nil {
log.Printf("error retrieving graph of dependencies: %v", err)
return "", nil, nil, fmt.Errorf("error retrieving graph of dependencies: %v", err)
}
return repoCache.DiggerYmlStr, &config, &projectsGraph, nil
}
func GetRepoByInstllationId(installationId int64, repoOwner string, repoName string) (*models.Repo, error) {
link, err := models.DB.GetGithubAppInstallationLink(installationId)
if err != nil {
log.Printf("Error getting GetGithubAppInstallationLink: %v", err)
return nil, fmt.Errorf("error getting github app link")
}
if link == nil {
log.Printf("Failed to find GithubAppInstallationLink for installationId: %v", installationId)
return nil, fmt.Errorf("error getting github app installation link")
}
diggerRepoName := repoOwner + "-" + repoName
repo, err := models.DB.GetRepo(link.Organisation.ID, diggerRepoName)
return repo, nil
}
func getBatchType(jobs []orchestrator_scheduler.Job) orchestrator_scheduler.DiggerBatchType {
allJobsContainApply := lo.EveryBy(jobs, func(job orchestrator_scheduler.Job) bool {
return lo.Contains(job.Commands, "digger apply")
})
if allJobsContainApply == true {
return orchestrator_scheduler.BatchTypeApply
} else {
return orchestrator_scheduler.BatchTypePlan
}
}
func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.IssueCommentEvent, ciBackendProvider ci_backends.CiBackendProvider, appId int64, postCommentHooks []IssueCommentHook) error {
defer func() {
if r := recover(); r != nil {
log.Printf("Recovered from panic in handleIssueCommentEvent handler: %v", r)
log.Printf("\n=== PANIC RECOVERED ===\n")
log.Printf("Error: %v\n", r)
log.Printf("Stack Trace:\n%s", string(debug.Stack()))
log.Printf("=== END PANIC ===\n")
}
}()
installationId := *payload.Installation.ID
repoName := *payload.Repo.Name
repoOwner := *payload.Repo.Owner.Login
repoFullName := *payload.Repo.FullName
cloneURL := *payload.Repo.CloneURL
issueNumber := *payload.Issue.Number
isDraft := payload.Issue.GetDraft()
userCommentId := *payload.GetComment().ID
actor := *payload.Sender.Login
commentBody := *payload.Comment.Body
defaultBranch := *payload.Repo.DefaultBranch
isPullRequest := payload.Issue.IsPullRequest()
labels := payload.Issue.Labels
prLabelsStr := lo.Map(labels, func(label *github.Label, i int) string {
return *label.Name
})
if !isPullRequest {
log.Printf("comment not on pullrequest, ignroning")
return nil
}
link, err := models.DB.GetGithubAppInstallationLink(installationId)
if err != nil {
log.Printf("Error getting GetGithubAppInstallationLink: %v", err)
return fmt.Errorf("error getting github app link")
}
orgId := link.OrganisationId
if *payload.Action != "created" {
log.Printf("comment is not of type 'created', ignoring")
return nil
}
if !strings.HasPrefix(*payload.Comment.Body, "digger") {
log.Printf("comment is not a Digger command, ignoring")
return nil
}
ghService, _, ghServiceErr := utils.GetGithubService(gh, installationId, repoFullName, repoOwner, repoName)
if ghServiceErr != nil {
log.Printf("GetGithubService error: %v", err)
return fmt.Errorf("error getting ghService to post error comment")
}
commentReporterManager := utils.InitCommentReporterManager(ghService, issueNumber)
if _, exists := os.LookupEnv("DIGGER_REPORT_BEFORE_LOADING_CONFIG"); exists {
_, err := commentReporterManager.UpdateComment(":construction_worker: Digger starting....")
if err != nil {
log.Printf("Error initializing comment reporter: %v", err)
return fmt.Errorf("error initializing comment reporter")
}
}
diggerYmlStr, ghService, config, projectsGraph, branch, commitSha, changedFiles, err := getDiggerConfigForPR(gh, orgId, prLabelsStr, installationId, repoFullName, repoOwner, repoName, cloneURL, issueNumber)
if err != nil {
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Could not load digger config, error: %v", err))
log.Printf("getDiggerConfigForPR error: %v", err)
return fmt.Errorf("error getting digger config")
}
// terraform code generator
if os.Getenv("DIGGER_GENERATION_ENABLED") == "1" {
err = GenerateTerraformFromCode(payload, commentReporterManager, config, defaultBranch, ghService, repoOwner, repoName, commitSha, issueNumber, branch)
if err != nil {
log.Printf("terraform generation failed: %v", err)
return err
}
}
commentIdStr := strconv.FormatInt(userCommentId, 10)
err = ghService.CreateCommentReaction(commentIdStr, string(dg_github.GithubCommentEyesReaction))
if err != nil {
log.Printf("CreateCommentReaction error: %v", err)
}
if !config.AllowDraftPRs && isDraft {
log.Printf("AllowDraftPRs is disabled, skipping PR: %v", issueNumber)
return nil
}
commentReporter, err := commentReporterManager.UpdateComment(":construction_worker: Digger starting.... config loaded successfully")
if err != nil {
log.Printf("Error initializing comment reporter: %v", err)
return fmt.Errorf("error initializing comment reporter")
}
diggerCommand, err := orchestrator_scheduler.GetCommandFromComment(*payload.Comment.Body)
if err != nil {
log.Printf("unknown digger command in comment: %v", *payload.Comment.Body)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Could not recognise comment, error: %v", err))
return fmt.Errorf("unknown digger command in comment %v", err)
}
prBranchName, _, err := ghService.GetBranchName(issueNumber)
if err != nil {
log.Printf("GetBranchName error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: GetBranchName error: %v", err))
return fmt.Errorf("error while fetching branch name")
}
impactedProjects, impactedProjectsSourceMapping, requestedProject, _, err := generic.ProcessIssueCommentEvent(issueNumber, *payload.Comment.Body, config, projectsGraph, ghService)
if err != nil {
log.Printf("Error processing event: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error processing event: %v", err))
return fmt.Errorf("error processing event")
}
log.Printf("GitHub IssueComment event processed successfully\n")
jobs, _, err := generic.ConvertIssueCommentEventToJobs(repoFullName, actor, issueNumber, commentBody, impactedProjects, requestedProject, config.Workflows, prBranchName, defaultBranch)
if err != nil {
log.Printf("Error converting event to jobs: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error converting event to jobs: %v", err))
return fmt.Errorf("error converting event to jobs")
}
log.Printf("GitHub IssueComment event converted to Jobs successfully\n")
// if flag set we dont allow more projects impacted than the number of changed files in PR (safety check)
if config2.LimitByNumOfFilesChanged() {
if len(impactedProjects) > len(changedFiles) {
log.Printf("Error the number impacted projects %v exceeds number of changed files: %v", len(impactedProjects), len(changedFiles))
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Error the number impacted projects %v exceeds number of changed files: %v", len(impactedProjects), len(changedFiles)))
log.Printf("Information about the event:")
log.Printf("GH payload: %v", payload)
log.Printf("PR changed files: %v", changedFiles)
log.Printf("digger.yml STR: %v", diggerYmlStr)
log.Printf("Parsed config: %v", config)
log.Printf("Dependency graph:")
spew.Dump(projectsGraph)
log.Printf("Impacted Projects: %v", impactedProjects)
log.Printf("Impacted Project jobs: %v", jobs)
return fmt.Errorf("error processing event")
}
}
// perform unlocking in backend
if config.PrLocks {
for _, project := range impactedProjects {
prLock := dg_locking.PullRequestLock{
InternalLock: locking.BackendDBLock{
OrgId: orgId,
},
CIService: ghService,
Reporter: comment_updater.NoopReporter{},
ProjectName: project.Name,
ProjectNamespace: repoFullName,
PrNumber: issueNumber,
}
err = dg_locking.PerformLockingActionFromCommand(prLock, *diggerCommand)
if err != nil {
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Failed perform lock action on project: %v %v", project.Name, err))
return fmt.Errorf("failed perform lock action on project: %v %v", project.Name, err)
}
}
}
// if commands are locking or unlocking we don't need to trigger any jobs
if *diggerCommand == orchestrator_scheduler.DiggerCommandUnlock ||
*diggerCommand == orchestrator_scheduler.DiggerCommandLock {
commentReporterManager.UpdateComment(fmt.Sprintf(":white_check_mark: Command %v completed successfully", *diggerCommand))
return nil
}
err = utils.ReportInitialJobsStatus(commentReporter, jobs)
if err != nil {
log.Printf("Failed to comment initial status for jobs: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: Failed to comment initial status for jobs: %v", err))
return fmt.Errorf("failed to comment initial status for jobs")
}
if len(jobs) == 0 {
log.Printf("no projects impacated, succeeding")
// This one is for aggregate reporting
err = utils.SetPRStatusForJobs(ghService, issueNumber, jobs)
return nil
}
err = utils.SetPRStatusForJobs(ghService, issueNumber, jobs)
if err != nil {
log.Printf("error setting status for PR: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: error setting status for PR: %v", err))
fmt.Errorf("error setting status for PR: %v", err)
}
impactedProjectsMap := make(map[string]dg_configuration.Project)
for _, p := range impactedProjects {
impactedProjectsMap[p.Name] = p
}
impactedProjectsJobMap := make(map[string]orchestrator_scheduler.Job)
for _, j := range jobs {
impactedProjectsJobMap[j.ProjectName] = j
}
reporterCommentId, err := strconv.ParseInt(commentReporter.CommentId, 10, 64)
if err != nil {
log.Printf("strconv.ParseInt error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not handle commentId: %v", err))
return fmt.Errorf("comment reporter error: %v", err)
}
var aiSummaryCommentId = ""
if config.Reporting.AiSummary {
aiSummaryComment, err := ghService.PublishComment(issueNumber, "AI Summary will be posted here after completion")
if err != nil {
log.Printf("could not post ai summary comment: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not post ai comment summary comment id: %v", err))
return fmt.Errorf("could not post ai summary comment: %v", err)
}
aiSummaryCommentId = aiSummaryComment.Id
}
batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, "github", orgId, impactedProjectsJobMap, impactedProjectsMap, projectsGraph, installationId, *branch, issueNumber, repoOwner, repoName, repoFullName, *commitSha, reporterCommentId, diggerYmlStr, 0, aiSummaryCommentId, config.ReportTerraformOutputs)
if err != nil {
log.Printf("ConvertJobsToDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
return fmt.Errorf("error convertingjobs")
}
if config.CommentRenderMode == dg_configuration.CommentRenderModeGroupByModule &&
(*diggerCommand == orchestrator_scheduler.DiggerCommandPlan || *diggerCommand == orchestrator_scheduler.DiggerCommandApply) {
sourceDetails, err := comment_updater.PostInitialSourceComments(ghService, issueNumber, impactedProjectsSourceMapping)
if err != nil {
log.Printf("PostInitialSourceComments error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: PostInitialSourceComments error: %v", err))
return fmt.Errorf("error posting initial comments")
}
batch, err := models.DB.GetDiggerBatch(batchId)
if err != nil {
log.Printf("GetDiggerBatch error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: PostInitialSourceComments error: %v", err))
return fmt.Errorf("error getting digger batch")
}
batch.SourceDetails, err = json.Marshal(sourceDetails)
if err != nil {
log.Printf("sourceDetails, json Marshal error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: json Marshal error: %v", err))
return fmt.Errorf("error marshalling sourceDetails")
}
err = models.DB.UpdateDiggerBatch(batch)
if err != nil {
log.Printf("UpdateDiggerBatch error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: UpdateDiggerBatch error: %v", err))
return fmt.Errorf("error updating digger batch")
}
}
segment.Track(strconv.Itoa(int(orgId)), "backend_trigger_job")
ciBackend, err := ciBackendProvider.GetCiBackend(
ci_backends.CiBackendOptions{
GithubClientProvider: gh,
GithubInstallationId: installationId,
GithubAppId: appId,
RepoName: repoName,
RepoOwner: repoOwner,
RepoFullName: repoFullName,
},
)
if err != nil {
log.Printf("GetCiBackend error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: GetCiBackend error: %v", err))
return fmt.Errorf("error fetching ci backed %v", err)
}
err = TriggerDiggerJobs(ciBackend, repoFullName, repoOwner, repoName, batchId, issueNumber, ghService, gh)
if err != nil {
log.Printf("TriggerDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: TriggerDiggerJobs error: %v", err))
return fmt.Errorf("error triggering Digger Jobs")
}
log.Printf("executing issue comment event post hooks:")
for _, hook := range postCommentHooks {
err := hook(gh, payload, ciBackendProvider)
if err != nil {
log.Printf("handleIssueCommentEvent post hook error: %v", err)
return fmt.Errorf("error during postevent hooks: %v", err)
}