Skip to content

Commit 79722a5

Browse files
jrryjcksnweave-e2e-quickstartjosecordaz
authored
Fix a fresh cluster with a repo that already has a deploy key (#410)
* first cut at fixing a fresh cluster with a repo that already has a deploy key * Fixed unit tests around deploy keys. - Updated git providers cache. - Added retries for reseted by per and deleting in progress errors. Co-authored-by: Jerry Jackson <[email protected]> Co-authored-by: Jose C Ordaz <[email protected]>
1 parent 617f412 commit 79722a5

File tree

8 files changed

+2007
-1422
lines changed

8 files changed

+2007
-1422
lines changed

pkg/gitproviders/cache/github.yaml

+1,549-852
Large diffs are not rendered by default.

pkg/gitproviders/cache/gitlab.yaml

+248-508
Large diffs are not rendered by default.

pkg/gitproviders/common.go

+19-38
Original file line numberDiff line numberDiff line change
@@ -207,52 +207,33 @@ func (h defaultGitProviderHandler) UploadDeployKey(owner, repoName string, deplo
207207
if err != nil {
208208
return fmt.Errorf("error getting org repo reference for owner %s, repo %s, %s ", owner, repoName, err)
209209
}
210-
_, err = orgRepo.DeployKeys().Get(ctx, deployKeyName)
210+
fmt.Println("uploading deploy key")
211+
_, err = orgRepo.DeployKeys().Create(ctx, deployKeyInfo)
211212
if err != nil {
212-
if errors.Is(err, gitprovider.ErrNotFound) {
213-
fmt.Println("uploading deploy key")
214-
_, err = orgRepo.DeployKeys().Create(ctx, deployKeyInfo)
215-
if err != nil {
216-
return fmt.Errorf("error uploading deploy key %s", err)
217-
}
218-
if err = utils.WaitUntil(os.Stdout, time.Second, time.Second*10, func() error {
219-
_, err = orgRepo.DeployKeys().Get(ctx, deployKeyName)
220-
return err
221-
}); err != nil {
222-
return fmt.Errorf("error getting deploy key %s for repo %s. %s", deployKeyName, repoName, err)
223-
}
224-
} else {
225-
return fmt.Errorf("error getting deploy key %s for repo %s. %s", deployKeyName, repoName, err)
226-
}
227-
} else {
228-
fmt.Printf("deploy key %s already exists for repo %s \n", deployKeyName, repoName)
213+
return fmt.Errorf("error uploading deploy key %s", err)
214+
}
215+
if err = utils.WaitUntil(os.Stdout, time.Second, time.Second*10, func() error {
216+
_, err = orgRepo.DeployKeys().Get(ctx, deployKeyName)
217+
return err
218+
}); err != nil {
219+
return fmt.Errorf("error verifying deploy key %s existance for repo %s. %s", deployKeyName, repoName, err)
229220
}
230-
231221
case AccountTypeUser:
232222
userRef := NewUserRepositoryRef(github.DefaultDomain, owner, repoName)
233223
userRepo, err := provider.UserRepositories().Get(ctx, userRef)
234224
if err != nil {
235225
return fmt.Errorf("error getting user repo reference for owner %s, repo %s, %s ", owner, repoName, err)
236226
}
237-
_, err = userRepo.DeployKeys().Get(ctx, deployKeyName)
238-
if err != nil && !strings.Contains(err.Error(), "key is already in use") {
239-
if errors.Is(err, gitprovider.ErrNotFound) {
240-
fmt.Println("uploading deploy key")
241-
_, err = userRepo.DeployKeys().Create(ctx, deployKeyInfo)
242-
if err != nil {
243-
return fmt.Errorf("error uploading deploy key %s", err)
244-
}
245-
if err = utils.WaitUntil(os.Stdout, time.Second, time.Second*10, func() error {
246-
_, err = userRepo.DeployKeys().Get(ctx, deployKeyName)
247-
return err
248-
}); err != nil {
249-
return fmt.Errorf("error getting deploy key %s for repo %s. %s", deployKeyName, repoName, err)
250-
}
251-
} else {
252-
return fmt.Errorf("error getting deploy key %s for repo %s. %s", deployKeyName, repoName, err)
253-
}
254-
} else {
255-
fmt.Printf("deploy key %s already exists for repo %s \n", deployKeyName, repoName)
227+
fmt.Println("uploading deploy key")
228+
_, err = userRepo.DeployKeys().Create(ctx, deployKeyInfo)
229+
if err != nil {
230+
return fmt.Errorf("error uploading deploy key %s", err)
231+
}
232+
if err = utils.WaitUntil(os.Stdout, time.Second, time.Second*10, func() error {
233+
_, err = userRepo.DeployKeys().Get(ctx, deployKeyName)
234+
return err
235+
}); err != nil {
236+
return fmt.Errorf("error verifying deploy key %s existance for repo %s. %s", deployKeyName, repoName, err)
256237
}
257238
default:
258239
return fmt.Errorf("account type not supported %s", ownerType)

pkg/gitproviders/common_test.go

+82-22
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
package gitproviders
22

33
import (
4+
"bytes"
45
"context"
56
"fmt"
7+
"github.com/stretchr/testify/assert"
8+
"io"
9+
"io/ioutil"
610
"math/rand"
711
"net/http"
812
"net/url"
913
"os"
1014
"strings"
15+
"sync"
1116
"testing"
1217
"time"
1318

14-
"github.com/stretchr/testify/assert"
15-
1619
"github.com/fluxcd/go-git-providers/gitlab"
1720
"github.com/weaveworks/weave-gitops/pkg/utils"
1821

@@ -34,6 +37,57 @@ var (
3437
GitlabUserTestName = "bot"
3538
)
3639

40+
type customTransport struct {
41+
transport http.RoundTripper
42+
mux *sync.Mutex
43+
}
44+
45+
func getBodyFromReaderWithoutConsuming(r *io.ReadCloser) string {
46+
body, _ := ioutil.ReadAll(*r)
47+
(*r).Close()
48+
*r = ioutil.NopCloser(bytes.NewBuffer(body))
49+
return string(body)
50+
}
51+
52+
const (
53+
ConnectionResetByPeer = "connection reset by peer"
54+
ProjectStillBeingDeleted = "The project is still being deleted"
55+
)
56+
57+
func (t *customTransport) RoundTrip(req *http.Request) (*http.Response, error) {
58+
t.mux.Lock()
59+
defer t.mux.Unlock()
60+
61+
var resp *http.Response
62+
var err error
63+
var responseBody string
64+
var requestBody string
65+
retryCount := 15
66+
for retryCount != 0 {
67+
responseBody = ""
68+
requestBody = ""
69+
if req != nil && req.Body != nil {
70+
requestBody = getBodyFromReaderWithoutConsuming(&req.Body)
71+
}
72+
resp, err = t.transport.RoundTrip(req)
73+
if resp != nil && resp.Body != nil {
74+
responseBody = getBodyFromReaderWithoutConsuming(&resp.Body)
75+
}
76+
if (err != nil && (strings.Contains(err.Error(), ConnectionResetByPeer))) ||
77+
strings.Contains(string(responseBody), ProjectStillBeingDeleted) {
78+
time.Sleep(4 * time.Second)
79+
if req != nil && req.Body != nil {
80+
req.Body = ioutil.NopCloser(strings.NewReader(requestBody))
81+
}
82+
retryCount--
83+
continue
84+
}
85+
break
86+
}
87+
88+
return resp, err
89+
}
90+
3791
func SetRecorder(recorder *recorder.Recorder) gitprovider.ChainableRoundTripperFunc {
3892
return func(transport http.RoundTripper) http.RoundTripper {
3993
recorder.SetTransport(transport)
@@ -143,17 +197,23 @@ func TestMain(m *testing.M) {
143197

144198
accounts := getAccounts()
145199

200+
t := customTransport{}
201+
146202
var err error
147203
cacheGithubRecorder, err := NewRecorder("github", accounts)
148204
if err != nil {
149205
panic(err)
150206
}
151207

208+
cacheGithubRecorder.SetTransport(&t)
209+
152210
cacheGitlabRecorder, err := NewRecorder("gitlab", accounts)
153211
if err != nil {
154212
panic(err)
155213
}
156214

215+
cacheGitlabRecorder.SetTransport(&t)
216+
157217
githubTestClient, err = newGithubTestClient(SetRecorder(cacheGithubRecorder))
158218
if err != nil {
159219
panic(err)
@@ -507,27 +567,25 @@ var _ = Describe("Test deploy keys creation", func() {
507567

508568
deployKey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBmym4XOiTj4rY3AcJKoJ8QupfgpFWtgNzDxzL0TrzfnurUQm+snozKLHGtOtS7PjMQsMaW9phyhhXv2KxadVI1uweFkC1TK4rPNWrqYX2g0JLXEScvaafSiv+SqozWLN/zhQ0e0jrtrYphtkd+H72RYsdq3mngY4WPJXM7z+HSjHSKilxj7XsxENt0dxT08LArxDC4OQXv9EYFgCyZ7SuLPBgA9160Co46Jm27enB/oBPx5zWd1MlkI+RtUi+XV2pLMzIpvYi2r2iWwOfDqE0N2cfpD0bY7cIOlv0iS7v6Qkmf7pBD+tRGTIZFcD5tGmZl1DOaeCZZ/VAN66aX+rN"
509569

510-
// Uncomment these when the recording is fixed
511-
512-
// exists, err := DeployKeyExists(accounts.GithubUserName, repoName)
513-
// Expect(err).ShouldNot(HaveOccurred())
514-
// Expect(exists).To(BeFalse())
570+
exists, err := DeployKeyExists(accounts.GithubUserName, repoName)
571+
Expect(err).ShouldNot(HaveOccurred())
572+
Expect(exists).To(BeFalse())
515573

516574
stdout := utils.CaptureStdout(func() {
517575
err = UploadDeployKey(accounts.GithubUserName, repoName, []byte(deployKey))
518576
Expect(err).ShouldNot(HaveOccurred())
519577
})
520578
Expect(stdout).To(Equal("uploading deploy key\n"))
521579

522-
// exists, err = DeployKeyExists(accounts.GithubUserName, repoName)
523-
// Expect(err).ShouldNot(HaveOccurred())
524-
// Expect(exists).To(BeTrue())
580+
exists, err = DeployKeyExists(accounts.GithubUserName, repoName)
581+
Expect(err).ShouldNot(HaveOccurred())
582+
Expect(exists).To(BeTrue())
525583

526584
stdout = utils.CaptureStdout(func() {
527585
err = UploadDeployKey(accounts.GithubUserName, repoName, []byte(deployKey))
528-
Expect(err).ShouldNot(HaveOccurred())
586+
Expect(err).Should(HaveOccurred())
529587
})
530-
Expect(stdout).To(Equal(fmt.Sprintf("deploy key weave-gitops-deploy-key already exists for repo %s \n", repoName)))
588+
Expect(stdout).To(Equal("uploading deploy key\n"))
531589

532590
ctx := context.Background()
533591
user, err := githubTestClient.UserRepositories().Get(ctx, userRepoRef)
@@ -541,6 +599,8 @@ var _ = Describe("Test deploy keys creation", func() {
541599

542600
accounts := getAccounts()
543601

602+
SetGithubProvider(githubTestClient)
603+
544604
repoName := "test-deploy-key-org-repo"
545605
orgRepoRef := NewOrgRepositoryRef(github.DefaultDomain, accounts.GithubOrgName, repoName)
546606
repoInfo := NewRepositoryInfo("test user repository", gitprovider.RepositoryVisibilityPrivate)
@@ -551,31 +611,31 @@ var _ = Describe("Test deploy keys creation", func() {
551611
err := CreateOrgRepository(githubTestClient, orgRepoRef, repoInfo, opts)
552612
Expect(err).ShouldNot(HaveOccurred())
553613
err = utils.WaitUntil(os.Stdout, time.Second, time.Second*30, func() error {
554-
return GetUserRepo(githubTestClient, accounts.GithubOrgName, repoName)
614+
return GetOrgRepo(githubTestClient, accounts.GithubOrgName, repoName)
555615
})
556616
Expect(err).ShouldNot(HaveOccurred())
557617

558-
deployKey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBmym4XOiTj4rY3AcJKoJ8QupfgpFWtgNzDxzL0TrzfnurUQm+snozKLHGtOtS7PjMQsMaW9phyhhXv2KxadVI1uweFkC1TK4rPNWrqYX2g0JLXEScvaafSiv+SqozWLN/zhQ0e0jrtrYphtkd+H72RYsdq3mngY4WPJXM7z+HSjHSKilxj7XsxENt0dxT08LArxDC4OQXv9EYFgCyZ7SuLPBgA9160Co46Jm27enB/oBPx5zWd1MlkI+RtUi+XV2pLMzIpvYi2r2iWwOfDqE0N2cfpD0bY7cIOlv0iS7v6Qkmf7pBD+tRGTIZFcD5tGmZl1DOaeCZZ/VAN66aX+rN"
618+
deployKey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDorjCI1Ai7xhZx4e2dYImHbjzbEc0gH1mjnkcb3Tqc5Zs/tQVxo282YIMeXq8IABt2AcwTzDHAviajbPqC05GNRwCmEFrYOnYKhMrdrKtYuCtmEhgnhPQlItXJlF00XwHfYetjfIzFSk8vdLJcwmGp6PPemDW2Xv6CPBAN23OGqTbYYsFuO7+hdU3CgGcR9WPDdzN7/4q1aq4Tk7qhNl5Yxw1DQ0OVgiAQnBJHeViOar14Dw1olhtzL2s88e/TE9t47p9iLXFXwN4irER25A4NUa7DYGpNfUEGQdlf1k81ctegQeA8fOZ4uT4zYSja7mG6QYRgPwN4ZB8ywTcHeON6EzWucSWKM4TcJgASmvJtJn5RifbuzMJTtqpCtIFmpo5/ItQFKYjI18Omqh0ZJe/P9YtYtM+Ac3FIOC0yKU7Ozsx/N7wq3uSIOTv8KCxkEgq2fBi9gF/+kE0BGSVao0RfY/fAUjS/ScuNvo30+MrW+8NmWeWRdhMJkJ25kLGuWBE="
559619

560-
// exists, err := DeployKeyExists(accounts.GithubUserName, repoName)
561-
// Expect(err).ShouldNot(HaveOccurred())
562-
// Expect(exists).To(BeFalse())
620+
exists, err := DeployKeyExists(accounts.GithubOrgName, repoName)
621+
Expect(err).ShouldNot(HaveOccurred())
622+
Expect(exists).To(BeFalse())
563623

564624
stdout := utils.CaptureStdout(func() {
565625
err = UploadDeployKey(accounts.GithubOrgName, repoName, []byte(deployKey))
566626
Expect(err).ShouldNot(HaveOccurred())
567627
})
568628
Expect(stdout).To(Equal("uploading deploy key\n"))
569629

570-
// exists, err = DeployKeyExists(accounts.GithubUserName, repoName)
571-
// Expect(err).ShouldNot(HaveOccurred())
572-
// Expect(exists).To(BeTrue())
630+
exists, err = DeployKeyExists(accounts.GithubOrgName, repoName)
631+
Expect(err).ShouldNot(HaveOccurred())
632+
Expect(exists).To(BeTrue())
573633

574634
stdout = utils.CaptureStdout(func() {
575635
err = UploadDeployKey(accounts.GithubOrgName, repoName, []byte(deployKey))
576-
Expect(err).ShouldNot(HaveOccurred())
636+
Expect(err).Should(HaveOccurred())
577637
})
578-
Expect(stdout).To(Equal(fmt.Sprintf("deploy key weave-gitops-deploy-key already exists for repo %s \n", repoName)))
638+
Expect(stdout).To(Equal("uploading deploy key\n"))
579639

580640
ctx := context.Background()
581641
user, err := githubTestClient.OrgRepositories().Get(ctx, orgRepoRef)

pkg/kube/kube.go

+13
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ type Kube interface {
4444
GetClusterName() (string, error)
4545
GetClusterStatus() ClusterStatus
4646
FluxPresent() (bool, error)
47+
SecretPresent(secretName string, namespace string) (bool, error)
4748
GetApplication(name string) (*wego.Application, error)
4849
}
4950

@@ -132,6 +133,18 @@ func (k *KubeClient) FluxPresent() (bool, error) {
132133
return true, nil
133134
}
134135

136+
// SecretPresent checks for a specific secret within a specified namespace
137+
func (k *KubeClient) SecretPresent(secretName, namespace string) (bool, error) {
138+
out, err := k.runKubectlCmd([]string{"get", "secret", secretName, "-n", namespace})
139+
if err != nil {
140+
if strings.Contains(string(out), "not found") {
141+
return false, nil
142+
}
143+
}
144+
145+
return true, nil
146+
}
147+
135148
func (k *KubeClient) GetApplication(name string) (*wego.Application, error) {
136149
cmd := []string{"get", "app", name, "-o", "json"}
137150
o, err := k.runKubectlCmd(cmd)

pkg/kube/kubefakes/fake_kube.go

+81
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)