-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathpost.go
923 lines (751 loc) · 26.3 KB
/
post.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
// SPDX-License-Identifier: Apache-2.0
package webhook
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/go-vela/server/api/build"
"github.com/go-vela/server/api/types"
"github.com/go-vela/server/compiler"
"github.com/go-vela/server/database"
"github.com/go-vela/server/internal"
"github.com/go-vela/server/queue"
"github.com/go-vela/server/scm"
"github.com/go-vela/server/util"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/library"
)
var baseErr = "unable to process webhook"
// swagger:operation POST /webhook base PostWebhook
//
// Deliver a webhook to the Vela API
//
// ---
// produces:
// - application/json
// parameters:
// - in: body
// name: body
// description: Webhook payload that we expect from the user or VCS
// required: true
// schema:
// "$ref": "#/definitions/Webhook"
// responses:
// '200':
// description: Successfully received the webhook but build was skipped
// schema:
// type: string
// '201':
// description: Successfully created the build from webhook
// type: json
// schema:
// "$ref": "#/definitions/Build"
// '400':
// description: Invalid request payload
// schema:
// "$ref": "#/definitions/Error"
// '401':
// description: Unauthorized
// schema:
// "$ref": "#/definitions/Error"
// '404':
// description: Not found
// schema:
// "$ref": "#/definitions/Error"
// '429':
// description: Concurrent build limit reached for repository
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unexpected server error
// schema:
// "$ref": "#/definitions/Error"
// PostWebhook represents the API handler to capture
// a webhook from a source control provider and
// publish it to the configure queue.
//
//nolint:funlen,gocyclo // ignore function length and cyclomatic complexity
func PostWebhook(c *gin.Context) {
// capture middleware values
m := c.MustGet("metadata").(*internal.Metadata)
l := c.MustGet("logger").(*logrus.Entry)
ctx := c.Request.Context()
l.Debug("webhook received")
// duplicate request so we can perform operations on the request body
//
// https://golang.org/pkg/net/http/#Request.Clone
dupRequest := c.Request.Clone(ctx)
// -------------------- Start of TODO: --------------------
//
// Remove the below code once http.Request.Clone()
// actually performs a deep clone.
//
// This code is required due to a known bug:
//
// * https://github.com/golang/go/issues/36095
// create buffer for reading request body
var buf bytes.Buffer
// read the request body for duplication
_, err := buf.ReadFrom(c.Request.Body)
if err != nil {
retErr := fmt.Errorf("unable to read webhook body: %w", err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// add the request body to the original request
c.Request.Body = io.NopCloser(&buf)
// add the request body to the duplicate request
dupRequest.Body = io.NopCloser(bytes.NewReader(buf.Bytes()))
//
// -------------------- End of TODO: --------------------
// process the webhook from the source control provider
//
// populate build, hook, repo resources as well as PR Number / PR Comment if necessary
webhook, err := scm.FromContext(c).ProcessWebhook(ctx, c.Request)
if err != nil {
retErr := fmt.Errorf("unable to parse webhook: %w", err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// check if the hook should be skipped
if skip, skipReason := webhook.ShouldSkip(); skip {
c.JSON(http.StatusOK, fmt.Sprintf("skipping build: %s", skipReason))
return
}
h, r, b := webhook.Hook, webhook.Repo, webhook.Build
l.Debugf("hook generated from SCM: %v", h)
l.Debugf("repo generated from SCM: %v", r)
// check if build was parsed from webhook.
if b == nil && h.GetEvent() != constants.EventRepository {
// typically, this should only happen on a webhook
// "ping" which gets sent when the webhook is created
c.JSON(http.StatusOK, "no build to process")
return
}
// check if repo was parsed from webhook
if r == nil {
retErr := fmt.Errorf("%s: failed to parse repo from webhook", baseErr)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
var repo *types.Repo
if h.GetEvent() == constants.EventRepository && (h.GetEventAction() == constants.ActionRenamed || h.GetEventAction() == constants.ActionTransferred) {
// get any matching hook with the repo's unique webhook ID in the SCM
hook, err := database.FromContext(c).GetHookByWebhookID(ctx, h.GetWebhookID())
if err != nil {
retErr := fmt.Errorf("%s: failed to get hook by webhook id for %s: %w", baseErr, r.GetFullName(), err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
// get the repo from the database using repo id of matching hook
repo, err = database.FromContext(c).GetRepo(ctx, hook.GetRepo().GetID())
if err != nil {
retErr := fmt.Errorf("%s: failed to get repo by id: %w", baseErr, err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
} else {
repo, err = database.FromContext(c).GetRepoForOrg(ctx, r.GetOrg(), r.GetName())
if err != nil {
retErr := fmt.Errorf("%s: failed to get repo %s: %w", baseErr, r.GetFullName(), err)
util.HandleError(c, http.StatusBadRequest, retErr)
return
}
}
// verify the webhook from the source control provider using DB repo hash
if c.Value("webhookvalidation").(bool) {
l.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
}).Tracef("verifying GitHub webhook for %s", r.GetFullName())
err = scm.FromContext(c).VerifyWebhook(ctx, dupRequest, repo)
if err != nil {
retErr := fmt.Errorf("unable to verify webhook: %w", err)
util.HandleError(c, http.StatusUnauthorized, retErr)
return
}
}
// if event is repository event, handle separately and return
if strings.EqualFold(h.GetEvent(), constants.EventRepository) {
r, err = handleRepositoryEvent(ctx, l, database.FromContext(c), m, h, r, repo)
if err != nil {
util.HandleError(c, http.StatusInternalServerError, err)
return
}
// if there were actual changes to the repo (database call populated ID field), return the repo object
if r.GetID() != 0 {
c.JSON(http.StatusOK, r)
return
}
c.JSON(http.StatusOK, "handled repository event, no build to process")
return
}
l.Debugf(`build author: %s,
build branch: %s,
build commit: %s,
build ref: %s`,
b.GetAuthor(), b.GetBranch(), b.GetCommit(), b.GetRef())
defer func() {
// send API call to update the webhook
_, err = database.FromContext(c).UpdateHook(ctx, h)
if err != nil {
l.Errorf("unable to update webhook %s/%d: %v", r.GetFullName(), h.GetNumber(), err)
}
l.WithFields(logrus.Fields{
"hook": h.GetNumber(),
"hook_id": h.GetID(),
"org": r.GetOrg(),
"repo": r.GetName(),
"repo_id": r.GetID(),
}).Info("hook updated")
}()
// attach a sender SCM id if the webhook payload from the SCM has no sender id
// the code in ProcessWebhook implies that the sender may not always be present
// fallbacks like pusher/commit_author do not have an id
if len(b.GetSenderSCMID()) == 0 || b.GetSenderSCMID() == "0" {
// fetch scm user id for pusher
senderID, err := scm.FromContext(c).GetUserID(ctx, b.GetSender(), repo.GetOwner().GetToken())
if err != nil {
retErr := fmt.Errorf("unable to assign sender SCM id: %w", err)
util.HandleError(c, http.StatusBadRequest, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
b.SetSenderSCMID(senderID)
}
// set the RepoID fields
b.SetRepo(repo)
h.SetRepo(repo)
// number of times to retry
retryLimit := 3
// implement a loop to process asynchronous operations with a retry limit
//
// Some operations taken during the webhook workflow can lead to race conditions
// failing to successfully process the request. This logic ensures we attempt our
// best efforts to handle these cases gracefully.
for i := 0; i < retryLimit; i++ {
// check if we're on the first iteration of the loop
if i > 0 {
// incrementally sleep in between retries
time.Sleep(time.Duration(i) * time.Second)
}
// send API call to capture the last hook for the repo
lastHook, err := database.FromContext(c).LastHookForRepo(ctx, repo)
if err != nil {
// format the error message with extra information
err = fmt.Errorf("unable to get last hook for repo %s: %w", r.GetFullName(), err)
// log the error for traceability
logrus.Error(err.Error())
// check if the retry limit has been exceeded
if i < retryLimit {
// continue to the next iteration of the loop
continue
}
retErr := fmt.Errorf("%s: %w", baseErr, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
// set the Number field
if lastHook != nil {
h.SetNumber(
lastHook.GetNumber() + 1,
)
}
// send API call to create the webhook
h, err = database.FromContext(c).CreateHook(ctx, h)
if err != nil {
// format the error message with extra information
err = fmt.Errorf("unable to create webhook %s/%d: %w", r.GetFullName(), h.GetNumber(), err)
// log the error for traceability
logrus.Error(err.Error())
// check if the retry limit has been exceeded
if i < retryLimit {
// continue to the next iteration of the loop
continue
}
retErr := fmt.Errorf("%s: %w", baseErr, err)
util.HandleError(c, http.StatusInternalServerError, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
// hook was created successfully
break
}
l.WithFields(logrus.Fields{
"hook": h.GetNumber(),
"hook_id": h.GetID(),
"org": repo.GetOrg(),
"repo": repo.GetName(),
}).Info("hook created")
// check if the repo is active
if !repo.GetActive() {
retErr := fmt.Errorf("%s: %s is not an active repo", baseErr, repo.GetFullName())
util.HandleError(c, http.StatusBadRequest, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
// verify the build has a valid event and the repo allows that event type
if !repo.GetAllowEvents().Allowed(b.GetEvent(), b.GetEventAction()) {
var actionErr string
if len(b.GetEventAction()) > 0 {
actionErr = ":" + b.GetEventAction()
}
retErr := fmt.Errorf("%s: %s does not have %s%s event enabled", baseErr, repo.GetFullName(), b.GetEvent(), actionErr)
util.HandleError(c, http.StatusBadRequest, retErr)
h.SetStatus(constants.StatusSkipped)
h.SetError(retErr.Error())
return
}
var (
prComment string
prLabels []string
)
if strings.EqualFold(b.GetEvent(), constants.EventComment) {
prComment = webhook.PullRequest.Comment
}
if strings.EqualFold(b.GetEvent(), constants.EventPull) {
prLabels = webhook.PullRequest.Labels
}
// construct CompileAndPublishConfig
config := build.CompileAndPublishConfig{
Build: b,
Metadata: m,
BaseErr: baseErr,
Source: "webhook",
Comment: prComment,
Labels: prLabels,
Retries: 3,
}
// generate the queue item
p, item, code, err := build.CompileAndPublish(
c,
config,
database.FromContext(c),
scm.FromContext(c),
compiler.FromContext(c),
queue.FromContext(c),
)
// error handling done in CompileAndPublish
if err != nil && code == http.StatusOK {
h.SetStatus(constants.StatusSkipped)
h.SetError(err.Error())
c.JSON(http.StatusOK, err.Error())
return
}
if err != nil {
h.SetStatus(constants.StatusFailure)
h.SetError(err.Error())
b.SetStatus(constants.StatusError)
util.HandleError(c, code, err)
err = scm.FromContext(c).Status(ctx, repo.GetOwner(), b, repo.GetOrg(), repo.GetName())
if err != nil {
l.Debugf("unable to set commit status for %s/%d: %v", repo.GetFullName(), b.GetNumber(), err)
}
return
}
// capture the build and repo from the items
b = item.Build
// set hook build
h.SetBuild(b)
// if event is deployment, update the deployment record to include this build
if strings.EqualFold(b.GetEvent(), constants.EventDeploy) {
d, err := database.FromContext(c).GetDeploymentForRepo(c, repo, webhook.Deployment.GetNumber())
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
deployment := webhook.Deployment
deployment.SetRepoID(repo.GetID())
deployment.SetBuilds([]*library.Build{b.ToLibrary()})
dr, err := database.FromContext(c).CreateDeployment(c, deployment)
if err != nil {
retErr := fmt.Errorf("%s: failed to create deployment %s/%d: %w", baseErr, repo.GetFullName(), deployment.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
l.WithFields(logrus.Fields{
"deployment": dr.GetNumber(),
"deployment_id": dr.GetID(),
"org": repo.GetOrg(),
"repo": repo.GetName(),
"repo_id": repo.GetID(),
}).Info("deployment created")
} else {
retErr := fmt.Errorf("%s: failed to get deployment %s/%d: %w", baseErr, repo.GetFullName(), webhook.Deployment.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
} else {
build := append(d.GetBuilds(), b.ToLibrary())
d.SetBuilds(build)
_, err := database.FromContext(c).UpdateDeployment(ctx, d)
if err != nil {
retErr := fmt.Errorf("%s: failed to update deployment %s/%d: %w", baseErr, repo.GetFullName(), d.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return
}
l.WithFields(logrus.Fields{
"deployment": d.GetNumber(),
"deployment_id": d.GetID(),
"org": repo.GetOrg(),
"repo": repo.GetName(),
"repo_id": repo.GetID(),
}).Info("deployment updated")
}
}
// regardless of whether the build is published to queue, we want to attempt to auto-cancel if no errors
defer func() {
if err == nil && build.ShouldAutoCancel(p.Metadata.AutoCancel, b, repo.GetBranch()) {
// fetch pending and running builds
rBs, err := database.FromContext(c).ListPendingAndRunningBuildsForRepo(c, repo)
if err != nil {
l.Errorf("unable to fetch pending and running builds for %s: %v", repo.GetFullName(), err)
}
l.WithFields(logrus.Fields{
"build": b.GetNumber(),
"build_id": b.GetID(),
"org": repo.GetOrg(),
"repo": repo.GetName(),
"repo_id": repo.GetID(),
}).Debugf("found %d pending/running builds", len(rBs))
for _, rB := range rBs {
// call auto cancel routine
canceled, err := build.AutoCancel(c, b, rB, p.Metadata.AutoCancel)
if err != nil {
// continue cancel loop if error, but log based on type of error
if canceled {
l.Errorf("unable to update canceled build error message: %v", err)
} else {
l.Errorf("unable to cancel running build: %v", err)
}
}
l.WithFields(logrus.Fields{
"build": rB.GetNumber(),
"build_id": rB.GetID(),
"org": repo.GetOrg(),
"repo": repo.GetName(),
"repo_id": repo.GetID(),
}).Debug("auto-canceled build")
}
}
}()
// track if we have already responded to the http request
// helps prevent multiple responses to the same request in the event of errors
responded := false
// if the webhook was from a Pull event from a forked repository, verify it is allowed to run
if webhook.PullRequest.IsFromFork {
l.Tracef("inside %s workflow for fork PR build %s/%d", repo.GetApproveBuild(), repo.GetFullName(), b.GetNumber())
switch repo.GetApproveBuild() {
case constants.ApproveForkAlways:
err = gatekeepBuild(c, b, repo)
if err != nil {
util.HandleError(c, http.StatusInternalServerError, err)
} else {
c.JSON(http.StatusCreated, b)
}
return
case constants.ApproveForkNoWrite:
// determine if build sender has write access to parent repo. If not, this call will result in an error
_, err = scm.FromContext(c).RepoAccess(ctx, b.GetSender(), repo.GetOwner().GetToken(), repo.GetOrg(), repo.GetName())
if err != nil {
err = gatekeepBuild(c, b, repo)
if err != nil {
util.HandleError(c, http.StatusInternalServerError, err)
} else {
c.JSON(http.StatusCreated, b)
}
return
}
l.Debugf("fork PR build %s/%d automatically running without approval", repo.GetFullName(), b.GetNumber())
case constants.ApproveOnce:
// determine if build sender is in the contributors list for the repo
//
// NOTE: this call is cumbersome for repos with lots of contributors. Potential TODO: improve this if
// GitHub adds a single-contributor API endpoint.
contributor, err := scm.FromContext(c).RepoContributor(ctx, repo.GetOwner(), b.GetSender(), repo.GetOrg(), repo.GetName())
if err != nil {
util.HandleError(c, http.StatusInternalServerError, err)
responded = true
}
if !contributor {
err = gatekeepBuild(c, b, repo)
if err != nil {
util.HandleError(c, http.StatusInternalServerError, err)
} else if !responded {
c.JSON(http.StatusCreated, b)
}
return
}
fallthrough
case constants.ApproveNever:
fallthrough
default:
l.Debugf("fork PR build %s/%d automatically running without approval", repo.GetFullName(), b.GetNumber())
}
}
// send API call to set the status on the commit
err = scm.FromContext(c).Status(ctx, repo.GetOwner(), b, repo.GetOrg(), repo.GetName())
if err != nil {
l.Errorf("unable to set commit status for %s/%d: %v", repo.GetFullName(), b.GetNumber(), err)
}
// publish the build to the queue
go build.Enqueue(
context.WithoutCancel(ctx),
queue.FromGinContext(c),
database.FromContext(c),
item,
b.GetHost(),
)
// respond only when necessary
if !responded {
c.JSON(http.StatusCreated, b)
}
}
// handleRepositoryEvent is a helper function that processes repository events from the SCM and updates
// the database resources with any relevant changes resulting from the event, such as name changes, transfers, etc.
//
// the caller is responsible for returning errors to the client.
func handleRepositoryEvent(ctx context.Context, l *logrus.Entry, db database.Interface, m *internal.Metadata, h *types.Hook, r *types.Repo, dbRepo *types.Repo) (*types.Repo, error) {
l = l.WithFields(logrus.Fields{
"event_type": h.GetEvent(),
})
l.Debugf("webhook is repository event, making necessary updates to repo %s", r.GetFullName())
defer func() {
// send API call to update the webhook
hr, err := db.CreateHook(ctx, h)
if err != nil {
l.Errorf("unable to create webhook %s/%d: %v", r.GetFullName(), h.GetNumber(), err)
}
l.WithFields(logrus.Fields{
"hook": hr.GetNumber(),
"hook_id": hr.GetID(),
"org": r.GetOrg(),
"repo": r.GetName(),
"repo_id": r.GetID(),
}).Info("hook created")
}()
switch h.GetEventAction() {
// if action is renamed or transferred, go through rename routine
case constants.ActionRenamed, constants.ActionTransferred:
r, err := RenameRepository(ctx, l, db, h, r, dbRepo, m)
if err != nil {
h.SetStatus(constants.StatusFailure)
h.SetError(err.Error())
return nil, err
}
return r, nil
// if action is archived, unarchived, or edited, perform edits to relevant repo fields
case "archived", "unarchived", constants.ActionEdited:
l.Debugf("repository action %s for %s", h.GetEventAction(), r.GetFullName())
// send call to get repository from database
dbRepo, err := db.GetRepoForOrg(ctx, r.GetOrg(), r.GetName())
if err != nil {
retErr := fmt.Errorf("%s: failed to get repo %s: %w", baseErr, r.GetFullName(), err)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return nil, retErr
}
// send API call to capture the last hook for the repo
lastHook, err := db.LastHookForRepo(ctx, dbRepo)
if err != nil {
retErr := fmt.Errorf("unable to get last hook for repo %s: %w", r.GetFullName(), err)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return nil, retErr
}
// set the Number field
if lastHook != nil {
h.SetNumber(
lastHook.GetNumber() + 1,
)
}
h.SetRepo(dbRepo)
// the only edits to a repo that impact Vela are to these three fields
if !strings.EqualFold(dbRepo.GetBranch(), r.GetBranch()) {
dbRepo.SetBranch(r.GetBranch())
}
if dbRepo.GetActive() != r.GetActive() {
dbRepo.SetActive(r.GetActive())
}
if !reflect.DeepEqual(dbRepo.GetTopics(), r.GetTopics()) {
dbRepo.SetTopics(r.GetTopics())
}
// update repo object in the database after applying edits
dbRepo, err = db.UpdateRepo(ctx, dbRepo)
if err != nil {
retErr := fmt.Errorf("%s: failed to update repo %s: %w", baseErr, r.GetFullName(), err)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return nil, err
}
l.WithFields(logrus.Fields{
"org": dbRepo.GetOrg(),
"repo": dbRepo.GetName(),
"repo_id": dbRepo.GetID(),
}).Info("repo updated")
return dbRepo, nil
// all other repo event actions are skippable
default:
return r, nil
}
}
// RenameRepository is a helper function that takes the old name of the repo,
// queries the database for the repo that matches that name and org, and updates
// that repo to its new name in order to preserve it. It also updates the secrets
// associated with that repo as well as build links for the UI.
//
// the caller is responsible for returning errors to the client.
func RenameRepository(ctx context.Context, l *logrus.Entry, db database.Interface, h *types.Hook, r *types.Repo, dbR *types.Repo, m *internal.Metadata) (*types.Repo, error) {
l = l.WithFields(logrus.Fields{
"event_type": h.GetEvent(),
})
l.Debugf("renaming repository from %s to %s", r.GetPreviousName(), r.GetName())
// update hook object which will be added to DB upon reaching deferred function in PostWebhook
h.SetRepo(r)
// send API call to capture the last hook for the repo
lastHook, err := db.LastHookForRepo(ctx, dbR)
if err != nil {
retErr := fmt.Errorf("unable to get last hook for repo %s: %w", r.GetFullName(), err)
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return nil, retErr
}
// set the Number field
if lastHook != nil {
h.SetNumber(
lastHook.GetNumber() + 1,
)
}
// get total number of secrets associated with repository
t, err := db.CountSecretsForRepo(ctx, dbR, map[string]interface{}{})
if err != nil {
return nil, fmt.Errorf("unable to get secret count for repo %s/%s: %w", dbR.GetOrg(), dbR.GetName(), err)
}
secrets := []*library.Secret{}
page := 1
// capture all secrets belonging to certain repo in database
for repoSecrets := int64(0); repoSecrets < t; repoSecrets += 100 {
s, _, err := db.ListSecretsForRepo(ctx, dbR, map[string]interface{}{}, page, 100)
if err != nil {
return nil, fmt.Errorf("unable to get secret list for repo %s/%s: %w", dbR.GetOrg(), dbR.GetName(), err)
}
secrets = append(secrets, s...)
page++
}
// update secrets to point to the new repository name
for _, secret := range secrets {
secret.SetOrg(r.GetOrg())
secret.SetRepo(r.GetName())
_, err = db.UpdateSecret(ctx, secret)
if err != nil {
return nil, fmt.Errorf("unable to update secret for repo %s/%s: %w", dbR.GetOrg(), dbR.GetName(), err)
}
l.WithFields(logrus.Fields{
"secret_id": secret.GetID(),
"repo": secret.GetRepo(),
"org": secret.GetOrg(),
}).Info("secret updated")
}
// get total number of builds associated with repository
t, err = db.CountBuildsForRepo(ctx, dbR, nil)
if err != nil {
return nil, fmt.Errorf("unable to get build count for repo %s: %w", dbR.GetFullName(), err)
}
builds := []*types.Build{}
page = 1
// capture all builds belonging to repo in database
for build := int64(0); build < t; build += 100 {
b, _, err := db.ListBuildsForRepo(ctx, dbR, nil, time.Now().Unix(), 0, page, 100)
if err != nil {
return nil, fmt.Errorf("unable to get build list for repo %s: %w", dbR.GetFullName(), err)
}
builds = append(builds, b...)
page++
}
// update build link to route to proper repo name
for _, build := range builds {
build.SetLink(
fmt.Sprintf("%s/%s/%d", m.Vela.WebAddress, r.GetFullName(), build.GetNumber()),
)
_, err = db.UpdateBuild(ctx, build)
if err != nil {
return nil, fmt.Errorf("unable to update build for repo %s: %w", dbR.GetFullName(), err)
}
l.WithFields(logrus.Fields{
"build_id": build.GetID(),
"build": build.GetNumber(),
"org": dbR.GetOrg(),
"repo": dbR.GetName(),
"repo_id": dbR.GetID(),
}).Info("build updated")
}
// update the repo name information
dbR.SetName(r.GetName())
dbR.SetOrg(r.GetOrg())
dbR.SetFullName(r.GetFullName())
dbR.SetClone(r.GetClone())
dbR.SetLink(r.GetLink())
dbR.SetPreviousName(r.GetPreviousName())
// update the repo in the database
dbR, err = db.UpdateRepo(ctx, dbR)
if err != nil {
retErr := fmt.Errorf("%s: failed to update repo %s/%s", baseErr, dbR.GetOrg(), dbR.GetName())
h.SetStatus(constants.StatusFailure)
h.SetError(retErr.Error())
return nil, retErr
}
l.WithFields(logrus.Fields{
"org": dbR.GetOrg(),
"repo": dbR.GetName(),
"repo_id": dbR.GetID(),
}).Infof("repo updated in database (previous name: %s)", r.GetPreviousName())
return dbR, nil
}
// gatekeepBuild is a helper function that will set the status of a build to 'pending approval' and
// send a status update to the SCM.
func gatekeepBuild(c *gin.Context, b *types.Build, r *types.Repo) error {
l := c.MustGet("logger").(*logrus.Entry)
l = l.WithFields(logrus.Fields{
"org": r.GetOrg(),
"repo": r.GetName(),
"repo_id": r.GetID(),
"build": b.GetNumber(),
"build_id": b.GetID(),
})
l.Debug("fork PR build waiting for approval")
b.SetStatus(constants.StatusPendingApproval)
_, err := database.FromContext(c).UpdateBuild(c, b)
if err != nil {
return fmt.Errorf("unable to update build for %s/%d: %w", r.GetFullName(), b.GetNumber(), err)
}
l.Info("build updated")
// update the build components to pending approval status
err = build.UpdateComponentStatuses(c, b, constants.StatusPendingApproval)
if err != nil {
return fmt.Errorf("unable to update build components for %s/%d: %w", r.GetFullName(), b.GetNumber(), err)
}
// send API call to set the status on the commit
err = scm.FromContext(c).Status(c, r.GetOwner(), b, r.GetOrg(), r.GetName())
if err != nil {
l.Errorf("unable to set commit status for %s/%d: %v", r.GetFullName(), b.GetNumber(), err)
}
return nil
}