/
syncer.go
1404 lines (1173 loc) · 42.2 KB
/
syncer.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 gitops
import (
"context"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/jlewi/hydros/pkg/gcp"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/jlewi/hydros/pkg/gitutil"
"github.com/jlewi/hydros/pkg/ecrutil"
"github.com/jlewi/hydros/pkg/skaffold"
kustomize2 "github.com/jlewi/hydros/pkg/kustomize"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"github.com/google/uuid"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/jlewi/hydros/api/v1alpha1"
"github.com/jlewi/hydros/pkg/github"
"github.com/jlewi/hydros/pkg/github/ghrepo"
"github.com/jlewi/hydros/pkg/util"
"github.com/pkg/errors"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kustomize "sigs.k8s.io/kustomize/api/types"
)
// Syncer keeps two repos in sync by creating PRs
// to publish hydrated manifests from one repo to the other.
type Syncer struct {
log logr.Logger
manifest *v1alpha1.ManifestSync
workDir string
sess *session.Session
transports *github.TransportManager
repoHelper *github.RepoHelper
execHelper *util.ExecHelper
// imageStrategies is a cache of how images should be resolved
imageStrategies map[util.DockerImageRef]v1alpha1.Strategy
selector *meta.LabelSelector
// Cache the Google image Resolver
gcpImageResovler *gcp.ImageResolver
}
const (
lastSyncFile = ".lastsync.yaml"
destKey = "dest"
sourceKey = "source"
forkKey = "fork"
kustomizationFile = "kustomization.yaml"
)
// NewSyncer creates a new syncer.
func NewSyncer(m *v1alpha1.ManifestSync, manager *github.TransportManager, opts ...SyncerOption) (*Syncer, error) {
if m == nil {
return nil, errors.Errorf("ManifestSync is required")
}
if err := m.IsValid(); err != nil {
return nil, err
}
if manager == nil {
return nil, fmt.Errorf("TransportManager is required")
}
s := &Syncer{
log: zapr.NewLogger(zap.L()),
workDir: "",
manifest: m,
transports: manager,
}
for _, o := range opts {
if err := o(s); err != nil {
return nil, err
}
}
s.log.Info("Creating NewSyncer", "manifest", m)
if s.workDir == "" {
newDir, err := os.MkdirTemp("", "manifestSync")
if err != nil {
return nil, errors.Wrapf(err, "Failed to create a temporary working directorry")
}
s.workDir = newDir
}
s.workDir = filepath.Join(s.workDir, m.Metadata.Name)
s.log.Info("workdir is set.", "workDir", s.workDir)
s.log = s.log.WithValues("ManifestSync.Name", s.manifest.Metadata.Name)
s.execHelper = &util.ExecHelper{
Log: s.log,
}
if s.manifest.Spec.Selector != nil {
selector, err := s.manifest.Spec.Selector.ToK8s()
if err != nil {
s.log.Error(err, "Failed to convert selector")
return nil, err
}
s.selector = selector
}
// Ensure we can get transports for each repo; this basically verifies the app is authorized
// for each repo.
for _, repo := range getRepos(*s.manifest) {
if _, err := s.transports.Get(repo.Org, repo.Repo); err != nil {
return nil, errors.Wrapf(err, "Failed to get transport for repo %v/%v; Is the GitHub app installed in that repo?", repo.Org, repo.Repo)
}
}
// Create a repo helper for the destRepo
dRepo := s.manifest.Spec.DestRepo
tr, err := s.transports.Get(dRepo.Org, dRepo.Repo)
if err != nil {
return nil, errors.Wrapf(err, "Failed to get transport for repo %v/%v; Is the GitHub app installed in that repo?", dRepo.Org, dRepo.Repo)
}
args := &github.RepoHelperArgs{
BaseRepo: ghrepo.New(dRepo.Org, dRepo.Repo),
GhTr: tr,
FullDir: filepath.Join(s.workDir, destKey),
Name: "hydros",
Email: "hydros@yourdomain.com",
Remote: "origin",
BranchName: s.manifest.Spec.ForkRepo.Branch,
BaseBranch: dRepo.Branch,
}
repoHelper, err := github.NewGithubRepoHelper(args)
if err != nil {
return nil, err
}
s.repoHelper = repoHelper
s.log.Info("Successfully created Syncer")
return s, nil
}
func getRepos(m v1alpha1.ManifestSync) map[string]v1alpha1.GitHubRepo {
return map[string]v1alpha1.GitHubRepo{
sourceKey: m.Spec.SourceRepo,
destKey: m.Spec.DestRepo,
forkKey: m.Spec.ForkRepo,
}
}
// SyncerOption is an option for instantiating the syncer.
type SyncerOption func(s *Syncer) error
// SyncWithLogger creates an option to use the supplied logger.
func SyncWithLogger(log logr.Logger) SyncerOption {
return func(s *Syncer) error {
s.log = log
return nil
}
}
// SyncWithWorkDir creates an option to use the supplied working directory.
func SyncWithWorkDir(wDir string) SyncerOption {
return func(s *Syncer) error {
s.workDir = wDir
return nil
}
}
// SyncWithAwsSession creates an option to use the supplied session.
func SyncWithAwsSession(sess *session.Session) SyncerOption {
return func(s *Syncer) error {
s.sess = sess
return nil
}
}
// getPinStrategy returns the strategy to resolve the image.
func (s *Syncer) getPinStrategy(source util.DockerImageRef) v1alpha1.Strategy {
if s.imageStrategies == nil {
s.imageStrategies = map[util.DockerImageRef]v1alpha1.Strategy{}
}
if _, ok := s.imageStrategies[source]; !ok {
for _, imageToPin := range s.manifest.Spec.ImageTagsToPin {
tagMatch := false
for _, t := range imageToPin.Tags {
if t == source.Tag {
tagMatch = true
break
}
}
if !tagMatch {
continue
}
if imageToPin.ImageRepoMatch == nil {
s.imageStrategies[source] = imageToPin.Strategy
break
}
repoMatches := false
for _, r := range imageToPin.ImageRepoMatch.Repos {
if r == source.Repo {
repoMatches = true
break
}
}
if repoMatches && imageToPin.ImageRepoMatch.Type == v1alpha1.IncludeRepo {
s.imageStrategies[source] = imageToPin.Strategy
}
if !repoMatches && imageToPin.ImageRepoMatch.Type == v1alpha1.ExcludeRepo {
s.imageStrategies[source] = imageToPin.Strategy
}
}
}
strategy, ok := s.imageStrategies[source]
if ok {
return strategy
}
return v1alpha1.UnknownStrategy
}
// RunOnce runs the syncer once. If force is true a sync is run even if none is needed.
func (s *Syncer) RunOnce(force bool) error {
// We need to reset the logger after RunOnce runs. Otherwise we will end up accumulating fields
// like "run".
oldLogger := s.log
defer func() {
s.log = oldLogger
}()
// Generate a unique run id for each run so that its easy to group log entries about a single run.
s.log = s.log.WithValues("run", uuid.New().String()[0:5])
ctx := context.Background()
ctx = logr.NewContext(ctx, s.log)
s.execHelper.Log = s.log
log := s.log
if _, err := os.Stat(s.workDir); os.IsNotExist(err) {
log.V(util.Debug).Info("Creating work directory.", "directory", s.workDir)
err = os.MkdirAll(s.workDir, util.FilePermUserGroup)
if err != nil {
return errors.Wrapf(err, "Failed to create dir: %v", s.workDir)
}
}
// Set the pauseStatus if needed
// This is necessary to ensure that the pausedUntil gets persisted when we update the manifest in git
// which causes it to get paused
if err := setPausedUntil(s.manifest); err != nil {
log.Error(err, "Failed to set pause status")
}
// Check if there is a PR already pending from the branch and if there is don't do a sync.
// If the fork is in a different repo then the head reference is OWNER:BRANCH
// If we are creating the PR from a different branch in the same repo as where we are creating
// the PR then we just use BRANCH as the ref
headBranchRef := s.manifest.Spec.ForkRepo.Branch
if s.manifest.Spec.ForkRepo.Org != s.manifest.Spec.DestRepo.Org {
headBranchRef = s.manifest.Spec.ForkRepo.Org + ":" + headBranchRef
}
existingPR, err := s.repoHelper.PullRequestForBranch()
if err != nil {
log.Error(err, "Failed to check if there is an existing PR", "headBranchRef", headBranchRef)
return err
}
if existingPR != nil {
log.Info("PR Already Exists; attempting to merge it.", "pr", existingPR.URL)
state, err := s.repoHelper.MergeAndWait(existingPR.Number, 3*time.Minute)
if err != nil {
log.Error(err, "Failed to Merge existing PR unable to continue with sync", "number", existingPR.Number, "pr", existingPR.URL)
return err
}
if state != github.ClosedState && state != github.MergedState {
log.Info("PR hasn't been merged; unable to continue with the sync", "number", existingPR.Number, "pr", existingPR.URL, "state", state)
return errors.Errorf("Existing PR %v is blocking sync", existingPR.URL)
}
}
if err := s.cloneRepos(); err != nil {
return err
}
sourceRepoRoot := filepath.Join(s.workDir, sourceKey)
sourceRoot := filepath.Join(sourceRepoRoot, s.manifest.Spec.SourcePath)
sourceCommit := s.getSourceCommit()
if err := s.buildImages(sourceRoot, sourceCommit); err != nil {
return err
}
lastStatus := s.lastStatusFromManifest(filepath.Join(s.workDir, destKey, s.manifest.Spec.DestPath, lastSyncFile))
// We need to take into account the current manifest and the lastStatus to deci
if isPaused(ctx, *s.manifest, *lastStatus, time.Now()) {
log.Info("Sync paused", "pausedUntil", lastStatus.PausedUntil)
return nil
}
if lastStatus.PausedUntil != nil {
log.Info("Sync pause has expired", "pausedUntil", lastStatus.PausedUntil)
}
// Walk the source repository and find all kustomization files.
kustomizeFiles, err := findKustomizationFiles(sourceRoot, sourceRepoRoot, s.manifest.Spec.ExcludeDirs, log)
if err != nil {
log.Error(err, "Failed to find kustomization files", "sourceRoot", sourceRoot)
return err
}
allImages, filesToHydrate, err := s.findImagesToPin(kustomizeFiles)
if err != nil {
return err
}
imagesToPin := map[util.DockerImageRef]v1alpha1.Strategy{}
// find the images to pin to.
pinnedImages := map[util.DockerImageRef]util.DockerImageRef{}
unResolved := []util.DockerImageRef{}
for source := range allImages {
// N.B. We make a copy of the tagged image because we will potentially modify its tag before
// resolving it. However, we want to preserve the original key when storing in pinnedImages.
taggedImage := source
strategy := s.getPinStrategy(source)
if strategy == v1alpha1.UnknownStrategy {
log.V(util.Debug).Info("Skipping image; doesn't need to be pinned", "image", source)
continue
}
imagesToPin[source] = strategy
// If the image is built from source then we want to change the tag of the image
// to be the source commit
if strategy == v1alpha1.SourceCommitStrategy {
log.V(util.Debug).Info("image built from source", "image", source, "oldTag", source.Tag, "newTag", sourceCommit)
taggedImage.Tag = sourceCommit
}
// All strategies require calling resolveImageToSha to resolve the image
// to a particular sha.
resolved, err := s.resolveImageToSha(taggedImage, strategy)
if err != nil {
// We want to accumulate a list of all unresolved images because its helpful to print a list of them
// all in the logs.
unResolved = append(unResolved, source)
log.Error(err, "Failed to resolve image.", "image", taggedImage, "strategy", strategy)
continue
}
pinnedImages[source] = resolved
log.V(util.Debug).Info("Resolved image", "source", source, "image", taggedImage, "resolved", resolved)
}
if len(unResolved) > 0 {
return fmt.Errorf("Not all images could be resolved; unresolved images: %v", unResolved)
}
// Check if the pinned images have changed.
changedImages := s.didImagesChange(lastStatus.PinnedImages, pinnedImages)
if sourceCommit == lastStatus.SourceCommit && len(changedImages) == 0 {
if !force {
log.Info("Sync not needed; manifests and images up to date", "sourceCommit", sourceCommit)
return nil
}
log.Info("Sync not needed but force is true", "sourceCommit", sourceCommit)
}
log.Info("Hydrated manifests need sync", "sourceCommit", sourceCommit, "lastSync", lastStatus.SourceCommit, "changedImages", changedImages)
// Set the images in the kustomization files.
for source, resolved := range pinnedImages {
// Loop over all the files containing this image
for _, t := range allImages[source] {
k, err := readKustomization(t.Kustomization)
if err != nil {
return err
}
// N.B wrap in a function to ensure defer is closed.
err = func() error {
err := util.SetKustomizeImage(k, t.ImageName, resolved)
if err != nil {
return err
}
w, err := os.Create(t.Kustomization)
if err != nil {
return errors.Wrapf(err, "Failed to Create file: %v", t.Kustomization)
}
defer func() { util.IgnoreError(w.Close()) }()
e := yaml.NewEncoder(w)
if err := e.Encode(k); err != nil {
log.Error(err, "Failed to marshal kustomization", "kustomization", k, "file", t.Kustomization)
return errors.Wrapf(err, "Failed Kustomization to file %v", t.Kustomization)
}
return nil
}()
if err != nil {
return err
}
}
}
// Create a local branch from the fork repo
forkDir := filepath.Join(s.workDir, forkKey)
// N.B We check out the branch of the destination repo.
cmd := exec.Command("git", "checkout", "-B", s.manifest.Spec.ForkRepo.Branch, "origin/"+s.manifest.Spec.DestRepo.Branch)
cmd.Dir = forkDir
if err := s.execHelper.Run(cmd); err != nil {
log.Error(err, "Failed to create a local branch for the forked repo")
return err
}
// Delete the target directory
baseHydratePath := filepath.Join(forkDir, s.manifest.Spec.DestPath)
if _, err := os.Stat(baseHydratePath); err == nil || os.IsExist(err) {
log.V(util.Debug).Info("Deleting dest path", "destPath", baseHydratePath)
if err := os.RemoveAll(baseHydratePath); err != nil {
return err
}
}
log.V(util.Debug).Info("Creating directory", "dir", baseHydratePath)
if err := os.MkdirAll(baseHydratePath, util.FilePermUserGroup); err != nil {
return errors.Wrapf(err, "Failed to create directory: %v", baseHydratePath)
}
// Hydrate overlay dirs
log.Info("Hydrating kustomizations", "kustomizations", filesToHydrate)
for _, k := range filesToHydrate {
targetPath, err := kustomize2.GenerateTargetPath(sourceRoot, k)
if err != nil {
log.Error(err, "Failed to generate target path", "kustomization", k)
return err
}
hydratePath := filepath.Join(baseHydratePath, targetPath.Dir)
if _, err := os.Stat(hydratePath); os.IsExist(err) {
newErr := fmt.Errorf("Hydrated path already exists; %v; kustomization:%v", hydratePath, k)
log.Error(newErr, "Hydrated directory already exists; This indicates two kustomizations are trying to hydrate the same package", "hydratePath", hydratePath, "kustomization", k)
return newErr
}
log.V(util.Debug).Info("Create kustomize output dir", "dir", hydratePath)
if err := os.MkdirAll(hydratePath, util.FilePermUserGroup); err != nil {
return errors.Wrapf(err, "Failed to create directory: %v", hydratePath)
}
overlayDir := path.Dir(k)
cmd := exec.Command("kustomize", "build", "--enable-helm", "--load-restrictor=LoadRestrictionsNone", "-o", hydratePath, overlayDir)
if err := s.execHelper.Run(cmd); err != nil {
log.Error(err, "Failed to hydrate kustomization", "overlayDir", overlayDir, "output", hydratePath)
return err
}
log.Info("Successfully hydrated package", "kustomization", k)
}
// Write the updated manifest to the dest
s.manifest.Status.SourceCommit = sourceCommit
s.manifest.Status.PinnedImages = []v1alpha1.PinnedImage{}
sourceRepo := s.manifest.Spec.SourceRepo
sourceURL := fmt.Sprintf("https://github.com/%v/%v/tree/%v", sourceRepo.Org, sourceRepo.Repo, sourceCommit)
s.manifest.Status.SourceURL = sourceURL
for old, new := range pinnedImages {
s.manifest.Status.PinnedImages = append(s.manifest.Status.PinnedImages, v1alpha1.PinnedImage{
Image: old.ToURL(),
NewImage: new.ToURL(),
})
}
err = s.applyKustomizeFns(baseHydratePath, sourceRoot, filesToHydrate)
if err != nil {
log.Error(err, "applyKustomizeFns failed")
return err
}
newSyncFile := filepath.Join(baseHydratePath, lastSyncFile)
w, err := os.Create(newSyncFile)
if err != nil {
log.Error(err, "Failed to write manifest", "path", newSyncFile)
return err
}
e := yaml.NewEncoder(w)
e.SetIndent(2)
if err := e.Encode(s.manifest); err != nil {
log.Error(err, "Failed to update manifest", "path", newSyncFile)
return err
}
// Commit and push the changes.
commands := [][]string{
{"git", "add", "."},
{"git", "commit", "-m", fmt.Sprintf("Update hydrated manifests to %v", sourceCommit)},
{"git", "push", "-f", "-u", "origin", "HEAD"},
}
for _, c := range commands {
cmd := exec.Command(c[0],
c[1:]...,
)
cmd.Dir = forkDir
if err := s.execHelper.Run(cmd); err != nil {
return err
}
}
// Create the PR.
prMessage := buildPrMessage(s.manifest, changedImages)
pr, err := s.repoHelper.CreatePr(prMessage, s.manifest.Spec.PrLabels)
if err != nil {
log.Error(err, "Failed to create pr")
return err
}
// EnableAutoMerge or merge the PR automatically. If you don't want the PR to be automerged you should
// set up appropriate branch protections e.g. require approvers.
// Wait up to 1 minute to try to merge the PR
// TODO(jeremy): This is mostly for dev takeover in the event we can't rely on automerge e.g. because
// we have a private repository for which we can't enable automerge. In this case we want to wait and
// retry the merge until its merged or we timeout. We may want to refactor this code so we can invoke the
// polling only in the case of being called with the takeover command.
// If the PR can't be merged does it make sense to report an error? in the case of long running tests
// The syncer can return and the PR will be merged either 1) when syncer is rerun or 2) by auto merge if enabled
// The desired behavior is potentially different in the takeover and non takeover setting.
state, err := s.repoHelper.MergeAndWait(pr.Number, 1*time.Minute)
if err != nil {
log.Error(err, "Failed to merge pr", "number", pr.Number, "url", pr.URL)
return err
}
if state != github.MergedState && state != github.ClosedState {
return fmt.Errorf("Failed to merge pr; state: %v", state)
}
log.Info("Sync succeeded")
return nil
}
// PushLocal commits any changes in wDir and then pushes those changes to the branch of the sourceRepo
// A sync can then be applied.
// keyFile is the private PEM key file to use. If not specified it will try to load one from the home directory
func (s *Syncer) PushLocal(wDir string, keyFile string) error {
log := s.log
if wDir == "" {
var err error
wDir, err = os.Getwd()
if err != nil {
return errors.Wrapf(err, "Failed to get current directory")
}
}
root, err := gitutil.LocateRoot(wDir)
if err != nil {
return errors.Wrapf(err, "Failed to locate git repo for %v", wDir)
}
if keyFile == "" {
home, err := os.UserHomeDir()
if err != nil {
return errors.Wrapf(err, "Could not get home directory")
}
keyFile = filepath.Join(home, ".ssh", "id_ed25519")
log.Info("No keyfile specified using default", "keyfile", keyFile)
}
// GitHub uses git for the username.
appAuth, err := ssh.NewPublicKeysFromFile("git", keyFile, "")
if err != nil {
return errors.Wrapf(err, "Failed to load ssh key from keyfile %v; is your SSH key password protected? Hydros currently requires no password to be set", keyFile)
}
log.Info("Located root of git repository", "root", root, "wDir", wDir)
// Open the repository
r, err := git.PlainOpenWithOptions(root, &git.PlainOpenOptions{})
if err != nil {
return errors.Wrapf(err, "Could not open respoistory at %v; ensure the directory contains a git repo", root)
}
// We need to identify the remote name for the source branch
// config reads .git/config
// We can use this to determine how the repository is setup to figure out what we need to do
cfg, err := r.Config()
if err != nil {
return err
}
message := "hydros automatically committing all files before running a sync."
w, err := r.Worktree()
if err != nil {
return errors.Wrapf(err, "Error getting worktree")
}
if err := gitutil.AddGitignoreToWorktree(w, root); err != nil {
return errors.Wrapf(err, "Failed to add gitignore patterns")
}
if err := gitutil.CommitAll(r, w, message); err != nil {
return err
}
org := s.manifest.Spec.SourceRepo.Org
repo := s.manifest.Spec.SourceRepo.Repo
sourceRepo := ghrepo.New(org, repo)
remoteName := func() string {
for _, r := range cfg.Remotes {
for _, u := range r.URLs {
remote, err := ghrepo.FromFullName(u)
if err != nil {
log.Error(err, "Could not parse URL for remote repository", "name", r.Name, "url", u)
}
if ghrepo.IsSame(sourceRepo, remote) {
return r.Name
}
}
}
return ""
}()
if remoteName == "" {
return errors.Errorf("Could not find remote repo for repository %v/%v", org, repo)
}
head, err := r.Head()
if err != nil {
return err
}
// The refspec to push
dst := fmt.Sprintf("refs/heads/%v", s.manifest.Spec.SourceRepo.Branch)
refSpec := head.Name().String() + ":" + dst
// Push changes to the remote branch.
if err := r.Push(&git.PushOptions{
RemoteName: remoteName,
RefSpecs: []config.RefSpec{
config.RefSpec(refSpec),
},
Progress: os.Stdout,
Force: true,
Auth: appAuth,
}); err != nil && err.Error() != "already up-to-date" {
return err
}
log.Info("Push succeeded")
return nil
}
// repoKeyToDir takes the key identifying a repo (e.g. "source", "dest", "fork") and returns the path where it is
// checked out.
func (s *Syncer) repoKeyToDir(name string) string {
return filepath.Join(s.workDir, name)
}
// cloneRepos clones all the repos
func (s *Syncer) cloneRepos() error {
log := s.log
// Clone the repos if its not already cloned.
for name, repoSpec := range getRepos(*s.manifest) {
fullDir := s.repoKeyToDir(name)
ghTr, err := s.transports.Get(repoSpec.Org, repoSpec.Repo)
if err != nil {
return fmt.Errorf("Missing transport for %v/%v", repoSpec.Org, repoSpec.Repo)
}
// Generate an access token
token, err := ghTr.Token(context.Background())
if err != nil {
return err
}
url := fmt.Sprintf("https://x-access-token:%v@github.com/%v/%v.git", token, repoSpec.Org, repoSpec.Repo)
log := log.WithValues("org", repoSpec.Org, "repo", repoSpec.Repo, "dir", fullDir)
err = func() error {
if _, err := os.Stat(fullDir); err == nil {
log.V(util.Debug).Info("Directory already exists")
return nil
}
commands := [][]string{
{"git", "clone", url, fullDir},
}
err := s.execHelper.RunCommands(commands, nil)
if err != nil {
log.Error(err, "git clone failed")
return err
}
return nil
}()
if err != nil {
return err
}
// Update the remote URL to refresh the token
// Then fetch it. Also make sure user name is set.
commands := [][]string{
{"git", "config", "user.name", "hydros"},
{"git", "config", "user.email", "hydros@notvalid.primer.ai"},
{"git", "remote", "set-url", "origin", url},
{"git", "fetch", "origin"},
// if we don't force code.abbrev to be 7 digits then we might get a variable
// number. We need the short hash to be consistent with the docker image
// tag otherwise we will fail to resolve images.
{"git", "config", "--local", "--add", "core.abbrev", "7"},
}
if err := s.execHelper.RunCommands(commands, func(cmd *exec.Cmd) {
cmd.Dir = fullDir
}); err != nil {
return err
}
// Drop any local changes that might be lingering from a previous run.
if err := s.resetBranch(fullDir); err != nil {
return err
}
cmd := exec.Command("git", "checkout", "origin/"+repoSpec.Branch)
cmd.Dir = fullDir
// N.B. use RunQuietly because we don't want to spam the logs when everything is working correctly.
if data, err := s.execHelper.RunQuietly(cmd); err != nil {
if name == forkKey {
// The checkout will fail if the origin branch doesn't already exist. This is fine.
// It means the manifests are out of sync and we will create the branch below.
log.V(util.Debug).Info("Ignoring failed checkout of forked branch; assuming it doesn't exist")
} else if name == destKey {
log.Error(err, "git checkout failed; the branch to merge the PR into doesn't exist. This usually means this is a new branch and you need to create it manually", "command", cmd.String(), "output", data)
return err
} else {
log.Error(err, "git checkout failed", "command", cmd.String(), "output", data)
return err
}
}
}
return nil
}
// didImagesChange checks whether the images are no longer pinned to the correct value.
func (s *Syncer) didImagesChange(lastSync []v1alpha1.PinnedImage, current map[util.DockerImageRef]util.DockerImageRef) []util.DockerImageRef {
log := s.log
changed := []util.DockerImageRef{}
lastImages := map[util.DockerImageRef]util.DockerImageRef{}
for _, image := range lastSync {
key, err := util.ParseImageURL(image.Image)
if err != nil {
log.Error(err, "Could not parse image", "image", image.Image)
continue
}
lastImage, err := util.ParseImageURL(image.NewImage)
if err != nil {
log.Error(err, "Could not parse image", "image", image.NewImage)
continue
}
lastImages[*key] = *lastImage
}
for image, newPinned := range current {
lastPinned, ok := lastImages[image]
if !ok {
log.V(util.Debug).Info("Found new image that needs pinning", "image", image)
changed = append(changed, newPinned)
continue
}
if lastPinned.ToURL() != newPinned.ToURL() {
log.V(util.Debug).Info("image changed", "mutable", image, "lastPinned", lastPinned, "newPinned", newPinned)
changed = append(changed, newPinned)
}
}
return changed
}
// RunPeriodically runs periodically with the specified period.
func (s *Syncer) RunPeriodically(period time.Duration) {
for {
err := s.RunOnce(false)
if err != nil {
s.log.Error(err, "Sync failed")
}
s.log.V(util.Debug).Info("sleep", "duration", period)
time.Sleep(period)
}
}
// lastStatusFromManifest reads the commit of the source from a YAML file containing a ManifestSync object
func (s *Syncer) lastStatusFromManifest(syncFile string) *v1alpha1.ManifestSyncStatus {
lastStatus := &v1alpha1.ManifestSyncStatus{
PinnedImages: []v1alpha1.PinnedImage{},
}
log := s.log
if _, err := os.Stat(syncFile); os.IsNotExist(err) {
log.Info("SyncFile doesn't exist", "syncFile", syncFile)
return lastStatus
}
r, err := os.Open(syncFile)
if err != nil {
// Just force a sync
log.Error(err, "Could not read sync file", "syncFile")
return lastStatus
}
d := yaml.NewDecoder(r)
lastSync := &v1alpha1.ManifestSync{}
if err := d.Decode(lastSync); err != nil {
log.Error(err, "Could not decode ManifestSync")
return lastStatus
}
return &lastSync.Status
}
// setPausedUntil checks for the annotation PauseAnnotation and sets the status to paused until the specified time
// if necessary
func setPausedUntil(s *v1alpha1.ManifestSync) error {
if s.Metadata.Annotations == nil {
return nil
}
timeJson, ok := s.Metadata.Annotations[v1alpha1.PauseAnnotation]
if !ok {
return nil
}
t := &metav1.Time{}
if err := t.UnmarshalJSON([]byte(timeJson)); err != nil {
return errors.Wrapf(err, "Failed to unmarshal the value of annotations %v; value %v", v1alpha1.PauseAnnotation, timeJson)
}
s.Status.PausedUntil = t
return nil
}
func (s *Syncer) getSourceCommit() string {
log := s.log
// Get the latest commit on the source repo
cmd := exec.Command("git", "rev-parse", "origin/"+s.manifest.Spec.SourceRepo.Branch)
cmd.Dir = filepath.Join(s.workDir, sourceKey)
output, err := cmd.CombinedOutput()
if err != nil {
log.Error(err, "Get latest commit failed", "command", cmd.String())
return ""
}
sourceCommit := strings.TrimSpace(string(output))
return sourceCommit
}
// imageAndFile is a tuple keeping track of a kustomization file
// and the name of an image to be replace
type imageAndFile struct {
ImageName string
Kustomization string
}
func (s *Syncer) resetBranch(repoDir string) error {
// Stash any changes
cmd := exec.Command("git", "stash", "save", "--keep-index", "--include-untracked")
cmd.Dir = repoDir
if err := s.execHelper.Run(cmd); err != nil {
return err
}
// Drop the changes
cmd = exec.Command("git", "stash", "drop")
cmd.Dir = repoDir
// Ignore git stash error it will return an error if there is nothing in the stash to drop
_ = cmd.Run()
// Hard reset is needed in case we have any tracked changes; this won't be dropped by stash
cmd = exec.Command("git", "reset", "--hard")
cmd.Dir = repoDir
if err := s.execHelper.Run(cmd); err != nil {
return err
}
return nil
}
// resolveImageToSha resolves the provided DockerImageRef to an image and gets the sha.
// If the image isn't found err will be an AwsError with code ecr.ErrCodeImageNotFoundException.
// See http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html for example of how to process it.
func (s *Syncer) resolveImageToSha(r util.DockerImageRef, strategy v1alpha1.Strategy) (util.DockerImageRef, error) {
log := s.log
if gcp.IsArtifactRegistry(r.Registry) {
if s.gcpImageResovler == nil {
log.Info("Creating GCP image resolver")
resolver, err := gcp.NewImageResolver(context.Background())
if err != nil {
return r, err
}
s.gcpImageResovler = resolver
}
return s.gcpImageResovler.ResolveImageToSha(r, strategy)
}
// Assume its ECR otherwise.
svc := ecr.New(s.sess)
resolved := r
input := &ecr.DescribeImagesInput{
ImageIds: []*ecr.ImageIdentifier{
{
ImageTag: aws.String(r.Tag),
},
},
RegistryId: aws.String(r.GetAwsRegistryID()),
RepositoryName: aws.String(r.Repo),
}
result, err := svc.DescribeImages(input)
if err != nil {
return resolved, err
}
if len(result.ImageDetails) != 1 {
s.log.Info("DescribeImages didn't return exactly one image", "image", r, "result", result)
return resolved, fmt.Errorf("BatchGetImage didn't return exactly one image")
}
image := result.ImageDetails[0]
resolved.Sha = *image.ImageDigest
if strategy == v1alpha1.MutableTagStrategy {
// we want try to replace it with a tag that is less
// likely to be mutable. This is mostly a hack for the case where the image is not built from the source repo.
// So we resolve it based on the mutable tag but we'd like to map its latest tag to the git commit tag.
excludedTags := map[string]bool{"latest": true, "live": true, "prod": true, "dev": true, "staging": true}
// Find the first tag if any not in excluded tags
// This is just so we can display images in the form of
// 1234.dkr.ecr.us-west-2.amazonaws.com/some-repo/some-image:d891862@sha256:1eaea2d03772c90f262bc17879e7a98129cec0d1db89611ed1ec6b206f5f1609
// The tag is helpful for humans but the sha takes precedence
for _, t := range image.ImageTags {
// Skip the original mutable tag.
if r.Tag == *t {
continue
}
if _, ok := excludedTags[*t]; !ok {