-
Notifications
You must be signed in to change notification settings - Fork 563
/
Copy pathstorage.go
1321 lines (1147 loc) · 44.4 KB
/
storage.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 models
import (
"encoding/json"
"errors"
"fmt"
"github.com/dchest/uniuri"
configuration "github.com/diggerhq/digger/libs/digger_config"
scheduler "github.com/diggerhq/digger/libs/scheduler"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/samber/lo"
"gorm.io/gorm"
"log"
"net/http"
"time"
)
func (db *Database) GetProjectsFromContext(c *gin.Context, orgIdKey string) ([]Project, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
log.Printf("getProjectsFromContext, org id: %v\n", loggedInOrganisationId)
if !exists {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
var projects []Project
err := db.GormDB.Preload("Organisation").Preload("Repo").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).Find(&projects).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
log.Printf("getProjectsFromContext, number of projects:%d\n", len(projects))
return projects, true
}
func (db *Database) GetReposFromContext(c *gin.Context, orgIdKey string) ([]Repo, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
log.Printf("GetReposFromContext, org id: %v\n", loggedInOrganisationId)
if !exists {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
var repos []Repo
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("repos.organisation_id = ?", loggedInOrganisationId).Find(&repos).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
log.Printf("GetReposFromContext, number of repos:%d\n", len(repos))
return repos, true
}
func (db *Database) GetPoliciesFromContext(c *gin.Context, orgIdKey string) ([]Policy, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
log.Printf("getPoliciesFromContext, org id: %v\n", loggedInOrganisationId)
if !exists {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
var policies []Policy
err := db.GormDB.Preload("Organisation").Preload("Repo").Preload("Project").
Joins("LEFT JOIN projects ON projects.id = policies.project_id").
Joins("LEFT JOIN repos ON projects.repo_id = repos.id").
Joins("LEFT JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).Find(&policies).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
log.Printf("getPoliciesFromContext, number of policies:%d\n", len(policies))
return policies, true
}
func (db *Database) GetProjectRunsForOrg(orgId int) ([]ProjectRun, error) {
var runs []ProjectRun
err := db.GormDB.Preload("Project").Preload("Project.Organisation").Preload("Project.Repo").
Joins("INNER JOIN projects ON projects.id = project_runs.project_id").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", orgId).Order("created_at desc").Limit(100).Find(&runs).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, fmt.Errorf("unknown error occurred while fetching database, %v\n", err)
}
log.Printf("getProjectRunsFromContext, number of runs:%d\n", len(runs))
return runs, nil
}
func (db *Database) GetProjectRunsFromContext(c *gin.Context, orgIdKey string) ([]ProjectRun, bool) {
loggedInOrganisationId := c.GetUint(orgIdKey)
log.Printf("getProjectRunsFromContext, org id: %v\n", loggedInOrganisationId)
if loggedInOrganisationId == 0 {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
runs, err := db.GetProjectRunsForOrg(int(loggedInOrganisationId))
if err != nil {
return nil, false
}
return runs, true
}
func (db *Database) GetProjectByRunId(c *gin.Context, runId uint, orgIdKey string) (*ProjectRun, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
if !exists {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
log.Printf("GetProjectByRunId, org id: %v\n", loggedInOrganisationId)
var projectRun ProjectRun
err := db.GormDB.Preload("Project").Preload("Project.Organisation").Preload("Project.Repo").
Joins("INNER JOIN projects ON projects.id = project_runs.project_id").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).
Where("project_runs.id = ?", runId).First(&projectRun).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
return &projectRun, true
}
func (db *Database) GetProjectByProjectId(c *gin.Context, projectId uint, orgIdKey string) (*Project, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
if !exists {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
log.Printf("GetProjectByProjectId, org id: %v\n", loggedInOrganisationId)
var project Project
err := db.GormDB.Preload("Organisation").Preload("Repo").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).
Where("projects.id = ?", projectId).First(&project).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
return &project, true
}
func (db *Database) GetProject(projectId uint) (*Project, error) {
log.Printf("GetProject, project id: %v\n", projectId)
var project Project
err := db.GormDB.Preload("Organisation").Preload("Repo").
Where("id = ?", projectId).
First(&project).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, err
}
return &project, nil
}
// GetProjectByName return project for specified org and repo
// if record doesn't exist return nil
func (db *Database) GetProjectByName(orgId any, repo *Repo, name string) (*Project, error) {
log.Printf("GetProjectByName, org id: %v, project name: %v\n", orgId, name)
var project Project
err := db.GormDB.Preload("Organisation").Preload("Repo").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", orgId).
Where("repos.id = ?", repo.ID).
Where("projects.name = ?", name).First(&project).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, err
}
return &project, nil
}
// GetProjectByRepo return projects for specified org and repo
func (db *Database) GetProjectByRepo(orgId any, repo *Repo) ([]Project, error) {
log.Printf("GetProjectByRepo, org id: %v, repo name: %v\n", orgId, repo.Name)
projects := make([]Project, 0)
err := db.GormDB.Preload("Organisation").Preload("Repo").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", orgId).
Where("repos.id = ?", repo.ID).Find(&projects).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, err
}
return projects, nil
}
func (db *Database) GetPolicyByPolicyId(c *gin.Context, policyId uint, orgIdKey string) (*Policy, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
if !exists {
c.String(http.StatusForbidden, "Not allowed to access this resource")
return nil, false
}
log.Printf("getPolicyByPolicyId, org id: %v\n", loggedInOrganisationId)
var policy Policy
err := db.GormDB.Preload("Project").Preload("Project.Organisation").Preload("Project.Repo").
Joins("INNER JOIN projects ON projects.id = policies.project_id").
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).
Where("policies.id = ?", policyId).First(&policy).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
return &policy, true
}
func (db *Database) GetDefaultRepo(c *gin.Context, orgIdKey string) (*Repo, bool) {
loggedInOrganisationId, exists := c.Get(orgIdKey)
if !exists {
log.Print("Not allowed to access this resource")
return nil, false
}
log.Printf("getDefaultRepo, org id: %v\n", loggedInOrganisationId)
var repo Repo
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ?", loggedInOrganisationId).First(&repo).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, false
}
return &repo, true
}
// GetRepo returns digger repo by organisationId and repo name (diggerhq-digger)
// it will return an empty object if record doesn't exist in database
func (db *Database) GetRepo(orgIdKey any, repoName string) (*Repo, error) {
var repo Repo
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ? AND repos.name=?", orgIdKey, repoName).First(&repo).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("repo not found %v", repoName)
}
log.Printf("Failed to find digger repo for orgId: %v, and repoName: %v, error: %v\n", orgIdKey, repoName, err)
return nil, err
}
return &repo, nil
}
// GetRepoById returns digger repo by organisationId and repo name (diggerhq-digger)
func (db *Database) GetRepoById(orgIdKey any, repoId any) (*Repo, error) {
var repo Repo
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ? AND repos.ID=?", orgIdKey, repoId).First(&repo).Error
if err != nil {
log.Printf("Failed to find digger repo for orgId: %v, and repoId: %v, error: %v\n", orgIdKey, repoId, err)
return nil, err
}
return &repo, nil
}
// GithubRepoAdded handles github drift that github repo has been added to the app installation
func (db *Database) GithubRepoAdded(installationId int64, appId int64, login string, accountId int64, repoFullName string) (*GithubAppInstallation, error) {
// check if item exist already
item := &GithubAppInstallation{}
result := db.GormDB.Where("github_installation_id = ? AND repo=? AND github_app_id=?", installationId, repoFullName, appId).First(item)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("failed to find github installation in database. %v", result.Error)
}
}
if result.RowsAffected == 0 {
var err error
item, err = db.CreateGithubAppInstallation(installationId, appId, login, int(accountId), repoFullName)
if err != nil {
return nil, fmt.Errorf("failed to save github installation item to database. %v", err)
}
} else {
log.Printf("Record for installation_id: %d, repo: %s, with status=active exist already.", installationId, repoFullName)
item.Status = GithubAppInstallActive
item.UpdatedAt = time.Now()
err := db.GormDB.Save(item).Error
if err != nil {
return nil, fmt.Errorf("failed to update github installation in the database. %v", err)
}
}
return item, nil
}
func (db *Database) GithubRepoRemoved(installationId int64, appId int64, repoFullName string) (*GithubAppInstallation, error) {
item := &GithubAppInstallation{}
err := db.GormDB.Where("github_installation_id = ? AND status=? AND github_app_id=? AND repo=?", installationId, GithubAppInstallActive, appId, repoFullName).First(item).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("Record not found for installationId: %d, status=active, githubAppId: %d and repo: %s", installationId, appId, repoFullName)
return nil, nil
}
return nil, fmt.Errorf("failed to find github installation in database. %v", err)
}
item.Status = GithubAppInstallDeleted
item.UpdatedAt = time.Now()
err = db.GormDB.Save(item).Error
if err != nil {
return nil, fmt.Errorf("failed to update github installation in the database. %v", err)
}
return item, nil
}
func (db *Database) GetGithubAppInstallationByOrgAndRepo(orgId any, repo string, status GithubAppInstallStatus) (*GithubAppInstallation, error) {
link, err := db.GetGithubInstallationLinkForOrg(orgId)
if err != nil {
return nil, err
}
installation := GithubAppInstallation{}
result := db.GormDB.Where("github_installation_id = ? AND status=? AND repo=?", link.GithubInstallationId, status, repo).Find(&installation)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
// If not found, the values will be default values, which means ID will be 0
if installation.ID == 0 {
return nil, nil
}
return &installation, nil
}
// GetGithubAppInstallationByIdAndRepo repoFullName should be in the following format: org/repo_name, for example "diggerhq/github-job-scheduler"
func (db *Database) GetGithubAppInstallationByIdAndRepo(installationId int64, repoFullName string) (*GithubAppInstallation, error) {
installation := GithubAppInstallation{}
result := db.GormDB.Where("github_installation_id = ? AND status=? AND repo=?", installationId, GithubAppInstallActive, repoFullName).Find(&installation)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
// If not found, the values will be default values, which means ID will be 0
if installation.Model.ID == 0 {
return nil, fmt.Errorf("GithubAppInstallation with id=%v doesn't exist", installationId)
}
return &installation, nil
}
func (db *Database) GetGithubAppInstallations(installationId int64) ([]GithubAppInstallation, error) {
var installations []GithubAppInstallation
result := db.GormDB.Where("github_installation_id = ? AND status=?", installationId, GithubAppInstallActive).Find(&installations)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return installations, nil
}
// GetGithubAppInstallationLink repoFullName should be in the following format: org/repo_name, for example "diggerhq/github-job-scheduler"
func (db *Database) GetGithubAppInstallationLink(installationId int64) (*GithubAppInstallationLink, error) {
var link GithubAppInstallationLink
result := db.GormDB.Preload("Organisation").Where("github_installation_id = ? AND status=?", installationId, GithubAppInstallationLinkActive).Find(&link)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
// If not found, the values will be default values, which means ID will be 0
if link.Model.ID == 0 {
return nil, nil
}
return &link, nil
}
func (db *Database) CreateGithubAppConnection(name string, githubId int64, ClientID string, ClientSecretEncrypted string, WebhookSecretEncrypted string, PrivateKeyEncrypted string, PrivateKeyBase64Encrypted string, Org string, url string, orgId uint) (*GithubAppConnection, error) {
app := GithubAppConnection{
Name: name,
GithubId: githubId,
ClientID: ClientID,
ClientSecretEncrypted: ClientSecretEncrypted,
WebhookSecretEncrypted: WebhookSecretEncrypted,
PrivateKeyEncrypted: PrivateKeyEncrypted,
PrivateKeyBase64Encrypted: PrivateKeyBase64Encrypted,
Org: Org,
GithubAppUrl: url,
OrganisationID: orgId,
}
result := db.GormDB.Save(&app)
if result.Error != nil {
return nil, result.Error
}
log.Printf("CreateGithubApp (name: %v, url: %v) has been created successfully\n", app.Name, app.GithubAppUrl)
return &app, nil
}
func (db *Database) GetGithubAppConnectionById(id string) (*GithubAppConnection, error) {
app := GithubAppConnection{}
result := db.GormDB.Where("id = ?", id).Find(&app)
if result.Error != nil {
log.Printf("Failed to find GitHub App for id: %v, error: %v\n", id, result.Error)
return nil, result.Error
}
return &app, nil
}
// GetGithubApp return GithubApp by Id
func (db *Database) GetGithubAppConnection(gitHubAppId any) (*GithubAppConnection, error) {
app := GithubAppConnection{}
result := db.GormDB.Where("github_id = ?", gitHubAppId).Find(&app)
if result.Error != nil {
log.Printf("Failed to find GitHub App for id: %v, error: %v\n", gitHubAppId, result.Error)
return nil, result.Error
}
return &app, nil
}
func (db *Database) CreateGithubInstallationLink(org *Organisation, installationId int64) (*GithubAppInstallationLink, error) {
l := GithubAppInstallationLink{}
// check if there is already a link to another org, and throw an error in this case
result := db.GormDB.Preload("Organisation").Where("github_installation_id = ? AND status=?", installationId, GithubAppInstallationLinkActive).Find(&l)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
if result.RowsAffected > 0 {
if l.OrganisationId != org.ID {
return nil, fmt.Errorf("GitHub app installation %v already linked to another org ", installationId)
}
log.Printf("installation %v has been linked to the org %v already.", installationId, org.Name)
// record already exist, do nothing
return &l, nil
}
var list []GithubAppInstallationLink
// if there are other installation for this org, we need to make them inactive
result = db.GormDB.Preload("Organisation").Where("github_installation_id <> ? AND organisation_id = ? AND status=?", installationId, org.ID, GithubAppInstallationLinkActive).Find(&list)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
for _, item := range list {
item.Status = GithubAppInstallationLinkInactive
db.GormDB.Save(&item)
}
link := GithubAppInstallationLink{Organisation: org, GithubInstallationId: installationId, Status: GithubAppInstallationLinkActive}
result = db.GormDB.Save(&link)
if result.Error != nil {
return nil, result.Error
}
log.Printf("GithubAppInstallationLink (org: %v, installationId: %v) has been created successfully\n", org.Name, installationId)
return &link, nil
}
func (db *Database) GetGithubInstallationLinkForOrg(orgId any) (*GithubAppInstallationLink, error) {
l := GithubAppInstallationLink{}
result := db.GormDB.Where("organisation_id = ? AND status=?", orgId, GithubAppInstallationLinkActive).Find(&l)
if result.Error != nil {
return nil, result.Error
}
if l.ID == 0 {
return nil, fmt.Errorf("GithubAppInstallationLink not found for orgId: %v\n", orgId)
}
return &l, nil
}
func (db *Database) GetGithubInstallationLinkForInstallationId(installationId any) (*GithubAppInstallationLink, error) {
l := GithubAppInstallationLink{}
result := db.GormDB.Where("github_installation_id = ? AND status=?", installationId, GithubAppInstallationLinkActive).Find(&l)
if result.Error != nil {
return nil, result.Error
}
return &l, nil
}
func (db *Database) MakeGithubAppInstallationLinkInactive(link *GithubAppInstallationLink) (*GithubAppInstallationLink, error) {
link.Status = GithubAppInstallationLinkInactive
result := db.GormDB.Save(link)
if result.Error != nil {
log.Printf("Failed to update GithubAppInstallationLink, id: %v, error: %v", link.ID, result.Error)
return nil, result.Error
}
return link, nil
}
func (db *Database) CreateDiggerJobLink(diggerJobId string, repoFullName string) (*GithubDiggerJobLink, error) {
link := GithubDiggerJobLink{Status: DiggerJobLinkCreated, DiggerJobId: diggerJobId, RepoFullName: repoFullName}
result := db.GormDB.Save(&link)
if result.Error != nil {
log.Printf("Failed to create GithubDiggerJobLink, %v, repo: %v \n", diggerJobId, repoFullName)
return nil, result.Error
}
log.Printf("GithubDiggerJobLink %v, (repo: %v) has been created successfully\n", diggerJobId, repoFullName)
return &link, nil
}
func (db *Database) GetDiggerJobLink(diggerJobId string) (*GithubDiggerJobLink, error) {
link := GithubDiggerJobLink{}
result := db.GormDB.Where("digger_job_id = ?", diggerJobId).Find(&link)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, nil
}
log.Printf("Failed to get DiggerJobLink, %v", diggerJobId)
return nil, result.Error
}
return &link, nil
}
func (db *Database) UpdateDiggerJobLink(diggerJobId string, repoFullName string, githubJobId int64) (*GithubDiggerJobLink, error) {
jobLink := GithubDiggerJobLink{}
// check if there is already a link to another org, and throw an error in this case
result := db.GormDB.Where("digger_job_id = ? AND repo_full_name=? ", diggerJobId, repoFullName).Find(&jobLink)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
log.Printf("Failed to update GithubDiggerJobLink, %v, repo: %v \n", diggerJobId, repoFullName)
return nil, result.Error
}
}
if result.RowsAffected == 1 {
jobLink.GithubJobId = githubJobId
result = db.GormDB.Save(&jobLink)
if result.Error != nil {
return nil, result.Error
}
log.Printf("GithubDiggerJobLink %v, (repo: %v) has been updated successfully\n", diggerJobId, repoFullName)
return &jobLink, nil
}
return &jobLink, nil
}
func (db *Database) GetOrganisationById(orgId any) (*Organisation, error) {
log.Printf("GetOrganisationById, orgId: %v, type: %T \n", orgId, orgId)
org := Organisation{}
err := db.GormDB.Where("id = ?", orgId).First(&org).Error
if err != nil {
return nil, fmt.Errorf("Error fetching organisation: %v\n", err)
}
return &org, nil
}
func (db *Database) GetDiggerBatch(batchId *uuid.UUID) (*DiggerBatch, error) {
batch := &DiggerBatch{}
result := db.GormDB.Where("id=? ", batchId).Find(batch)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return batch, nil
}
func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationId int64, repoOwner string, repoName string, repoFullname string, PRNumber int, diggerConfig string, branchName string, batchType scheduler.DiggerCommand, commentId *int64, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutputs bool) (*DiggerBatch, error) {
uid := uuid.New()
batch := &DiggerBatch{
ID: uid,
VCS: vcsType,
GithubInstallationId: githubInstallationId,
RepoOwner: repoOwner,
RepoName: repoName,
RepoFullName: repoFullname,
PrNumber: PRNumber,
CommentId: commentId,
Status: scheduler.BatchJobCreated,
BranchName: branchName,
DiggerConfig: diggerConfig,
BatchType: batchType,
GitlabProjectId: gitlabProjectId,
AiSummaryCommentId: aiSummaryCommentId,
ReportTerraformOutputs: reportTerraformOutputs,
}
result := db.GormDB.Save(batch)
if result.Error != nil {
return nil, result.Error
}
log.Printf("DiggerBatch (id: %v) has been created successfully\n", batch.ID)
return batch, nil
}
func (db *Database) UpdateDiggerBatch(batch *DiggerBatch) error {
result := db.GormDB.Save(batch)
if result.Error != nil {
return result.Error
}
log.Printf("batch %v has been updated successfully\n", batch.ID)
return nil
}
func (db *Database) UpdateBatchStatus(batch *DiggerBatch) error {
if batch.Status == scheduler.BatchJobInvalidated || batch.Status == scheduler.BatchJobFailed || batch.Status == scheduler.BatchJobSucceeded {
return nil
}
batchId := batch.ID
var diggerJobs []DiggerJob
result := db.GormDB.Where("batch_id=?", batchId).Find(&diggerJobs)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
log.Printf("Failed to get DiggerJob by batch id: %v, error: %v\n", batchId, result.Error)
}
return result.Error
}
allJobsSucceeded := true
for _, job := range diggerJobs {
if job.Status != scheduler.DiggerJobSucceeded {
allJobsSucceeded = false
}
}
if allJobsSucceeded == true {
batch.Status = scheduler.BatchJobSucceeded
}
return nil
}
func (db *Database) CreateDiggerJob(batchId uuid.UUID, serializedJob []byte, workflowFile string) (*DiggerJob, error) {
if serializedJob == nil || len(serializedJob) == 0 {
return nil, fmt.Errorf("serializedJob can't be empty")
}
jobId := uniuri.New()
batchIdStr := batchId.String()
summary := &DiggerJobSummary{}
result := db.GormDB.Save(summary)
if result.Error != nil {
return nil, result.Error
}
workflowUrl := "#"
job := &DiggerJob{DiggerJobID: jobId, Status: scheduler.DiggerJobCreated,
BatchID: &batchIdStr, SerializedJobSpec: serializedJob, DiggerJobSummary: *summary, WorkflowRunUrl: &workflowUrl, WorkflowFile: workflowFile}
result = db.GormDB.Save(job)
if result.Error != nil {
return nil, result.Error
}
log.Printf("DiggerJob %v, (id: %v) has been created successfully\n", job.DiggerJobID, job.ID)
return job, nil
}
func (db *Database) ListDiggerRunsForProject(projectName string, repoId uint) ([]DiggerRun, error) {
var runs []DiggerRun
err := db.GormDB.Preload("PlanStage").Preload("ApplyStage").
Where("project_name = ? AND repo_id= ?", projectName, repoId).Order("created_at desc").Find(&runs).Error
if err != nil {
log.Printf("Unknown error occurred while fetching database, %v\n", err)
return nil, err
}
log.Printf("ListDiggerRunsForProject, number of runs:%d\n", len(runs))
return runs, nil
}
func (db *Database) CreateDiggerRun(Triggertype string, PrNumber int, Status DiggerRunStatus, CommitId string, DiggerConfig string, GithubInstallationId int64, RepoId uint, ProjectName string, RunType RunType, planStageId *uint, applyStageId *uint) (*DiggerRun, error) {
dr := &DiggerRun{
Triggertype: Triggertype,
PrNumber: &PrNumber,
Status: Status,
CommitId: CommitId,
DiggerConfig: DiggerConfig,
GithubInstallationId: GithubInstallationId,
RepoId: RepoId,
ProjectName: ProjectName,
RunType: RunType,
PlanStageId: planStageId,
ApplyStageId: applyStageId,
IsApproved: false,
}
result := db.GormDB.Save(dr)
if result.Error != nil {
log.Printf("Failed to create DiggerRun: %v, error: %v\n", dr.ID, result.Error)
return nil, result.Error
}
log.Printf("DiggerRun %v, has been created successfully\n", dr.ID)
return dr, nil
}
func (db *Database) CreateDiggerRunStage(batchId string) (*DiggerRunStage, error) {
drs := &DiggerRunStage{
BatchID: &batchId,
}
result := db.GormDB.Save(drs)
if result.Error != nil {
log.Printf("Failed to create DiggerRunStage: %v, error: %v\n", drs.ID, result.Error)
return nil, result.Error
}
log.Printf("DiggerRunStage %v, has been created successfully\n", drs.ID)
return drs, nil
}
func (db *Database) GetLastDiggerRunForProject(projectName string) (*DiggerRun, error) {
diggerRun := &DiggerRun{}
result := db.GormDB.Where("project_name = ? AND status <> ?", projectName, RunQueued).Order("created_at Desc").First(diggerRun)
if result.Error != nil {
log.Printf("error while fetching last digger run: %v", result.Error)
return nil, result.Error
}
return diggerRun, nil
}
func (db *Database) GetDiggerRun(id uint) (*DiggerRun, error) {
dr := &DiggerRun{}
result := db.GormDB.Preload("Repo").
Preload("ApplyStage").
Preload("PlanStage").
Where("id=? ", id).Find(dr)
if result.Error != nil {
return nil, result.Error
}
return dr, nil
}
func (db *Database) CreateDiggerRunQueueItem(diggeRrunId uint, projectId uint) (*DiggerRunQueueItem, error) {
drq := &DiggerRunQueueItem{
DiggerRunId: diggeRrunId,
ProjectId: projectId,
}
result := db.GormDB.Save(drq)
if result.Error != nil {
log.Printf("Failed to create DiggerRunQueueItem: %v, error: %v\n", drq.ID, result.Error)
return nil, result.Error
}
log.Printf("DiggerRunQueueItem %v, has been created successfully\n", drq.ID)
return drq, nil
}
func (db *Database) GetDiggerRunQueueItem(id uint) (*DiggerRunQueueItem, error) {
dr := &DiggerRunQueueItem{}
result := db.GormDB.Preload("DiggerRun").Where("id=? ", id).Find(dr)
if result.Error != nil {
return nil, result.Error
}
return dr, nil
}
func (db *Database) GetDiggerJobFromRunStage(stage DiggerRunStage) (*DiggerJob, error) {
job := &DiggerJob{}
result := db.GormDB.Preload("Batch").Take(job, "batch_id = ?", stage.BatchID)
if result.Error != nil {
return nil, result.Error
}
return job, nil
}
func (db *Database) UpdateDiggerRun(diggerRun *DiggerRun) error {
result := db.GormDB.Save(diggerRun)
if result.Error != nil {
return result.Error
}
log.Printf("diggerRun %v has been updated successfully\n", diggerRun.ID)
return nil
}
func (db *Database) DequeueRunItem(queueItem *DiggerRunQueueItem) error {
log.Printf("DiggerRunQueueItem Deleting: %v", queueItem.ID)
result := db.GormDB.Delete(queueItem)
if result.Error != nil {
return result.Error
}
log.Printf("diggerRunQueueItem %v has been deleted successfully\n", queueItem.ID)
return nil
}
func (db *Database) GetFirstRunQueueForEveryProject() ([]DiggerRunQueueItem, error) {
var runqueues []DiggerRunQueueItem
query := `WITH RankedRuns AS (
SELECT
digger_run_queue_items.digger_run_id,
digger_run_queue_items.project_id,
digger_run_queue_items.created_at,
ROW_NUMBER() OVER (PARTITION BY digger_run_queue_items.project_id ORDER BY digger_run_queue_items.created_at ASC) AS QueuePosition
FROM
digger_run_queue_items
)
SELECT
RankedRuns.digger_run_id ,
RankedRuns.project_id ,
RankedRuns.created_at
FROM
RankedRuns
WHERE
QueuePosition = 1`
// 1. Fetch the front of the queue for every projectID
tx := db.GormDB.
Raw(query).
Find(&runqueues)
if tx.Error != nil {
fmt.Printf("%v", tx.Error)
return nil, tx.Error
}
// 2. Preload Project and DiggerRun for every DiggerrunQueue item (front of queue)
var runqueuesWithData []DiggerRunQueueItem
diggerRunIds := lo.Map(runqueues, func(run DiggerRunQueueItem, index int) uint {
return run.DiggerRunId
})
tx = db.GormDB.Preload("DiggerRun").Preload("DiggerRun.Repo").
Preload("DiggerRun.PlanStage").Preload("DiggerRun.ApplyStage").
Preload("DiggerRun.PlanStage.Batch").Preload("DiggerRun.ApplyStage.Batch").
Where("digger_run_queue_items.digger_run_id in ?", diggerRunIds).Find(&runqueuesWithData)
if tx.Error != nil {
fmt.Printf("%v", tx.Error)
return nil, tx.Error
}
return runqueuesWithData, nil
}
func (db *Database) UpdateDiggerJobSummary(diggerJobId string, resourcesCreated uint, resourcesUpdated uint, resourcesDeleted uint) (*DiggerJob, error) {
diggerJob, err := db.GetDiggerJob(diggerJobId)
if err != nil {
return nil, fmt.Errorf("Could not get digger job")
}
var jobSummary *DiggerJobSummary
jobSummary = &diggerJob.DiggerJobSummary
jobSummary.ResourcesCreated = resourcesCreated
jobSummary.ResourcesUpdated = resourcesUpdated
jobSummary.ResourcesDeleted = resourcesDeleted
result := db.GormDB.Save(&jobSummary)
if result.Error != nil {
return nil, result.Error
}
log.Printf("DiggerJob %v summary has been updated successfully\n", diggerJobId)
return diggerJob, nil
}
func (db *Database) UpdateDiggerJob(job *DiggerJob) error {
result := db.GormDB.Save(job)
if result.Error != nil {
return result.Error
}
log.Printf("DiggerJob %v, (id: %v) has been updated successfully\n", job.DiggerJobID, job.ID)
return nil
}
func (db *Database) GetDiggerJobsForBatch(batchId uuid.UUID) ([]DiggerJob, error) {
jobs := make([]DiggerJob, 0)
var where *gorm.DB
where = db.GormDB.Where("digger_jobs.batch_id = ?", batchId)
result := where.Preload("Batch").Preload("DiggerJobSummary").Find(&jobs)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return jobs, nil
}
func (db *Database) GetDiggerJobsForBatchWithStatus(batchId uuid.UUID, status []scheduler.DiggerJobStatus) ([]DiggerJob, error) {
jobs := make([]DiggerJob, 0)
var where *gorm.DB
where = db.GormDB.Where("digger_jobs.batch_id = ?", batchId).Where("status IN ?", status)
result := where.Preload("Batch").Preload("DiggerJobSummary").Find(&jobs)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return jobs, nil
}
func (db *Database) GetDiggerJobsWithStatus(status scheduler.DiggerJobStatus) ([]DiggerJob, error) {
jobs := make([]DiggerJob, 0)
var where *gorm.DB
where = db.GormDB.Where("status = ?", status)
result := where.Preload("Batch").Find(&jobs)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return jobs, nil
}
func (db *Database) GetPendingParentDiggerJobs(batchId *uuid.UUID) ([]DiggerJob, error) {
jobs := make([]DiggerJob, 0)
joins := db.GormDB.Joins("LEFT JOIN digger_job_parent_links ON digger_jobs.digger_job_id = digger_job_parent_links.digger_job_id").Preload("Batch")
var where *gorm.DB
if batchId != nil {
where = joins.Where("digger_jobs.status = ? AND digger_job_parent_links.id IS NULL AND digger_jobs.batch_id = ?", scheduler.DiggerJobCreated, *batchId)
} else {
where = joins.Where("digger_jobs.status = ? AND digger_job_parent_links.id IS NULL", scheduler.DiggerJobCreated)
}
result := where.Find(&jobs)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return jobs, nil
}
func (db *Database) GetDiggerJob(jobId string) (*DiggerJob, error) {
job := &DiggerJob{}
result := db.GormDB.Preload("Batch").Preload("DiggerJobSummary").Where("digger_job_id=? ", jobId).Find(job)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, result.Error
}
}
return job, nil
}
func (db *Database) GetDiggerJobParentLinksByParentId(parentId *string) ([]DiggerJobParentLink, error) {
var jobParentLinks []DiggerJobParentLink
result := db.GormDB.Where("parent_digger_job_id=?", parentId).Find(&jobParentLinks)
if result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
log.Printf("Failed to get DiggerJobLink by parent job id: %v, error: %v\n", parentId, result.Error)
return nil, result.Error
}
}
return jobParentLinks, nil
}