Skip to content

Commit bbf4540

Browse files
author
Drew Wells
authored
PTEUDO-1096 perform reconcile tests on PR builds (#251)
Stand up a local postgres for testing Fix many issues within the initial test suite that caused reconcile to fail
1 parent 9b9f864 commit bbf4540

14 files changed

+691
-287
lines changed

Jenkinsfile

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ pipeline {
1818
sudo apt-get update
1919
2020
if ! which psql > /dev/null; then
21+
22+
23+
timeout 300 bash -c -- 'while sudo fuser /var/lib/dpkg/lock-frontend > /dev/null 2>&1
24+
do
25+
echo "Waiting to get lock /var/lib/dpkg/lock-frontend..."
26+
sleep 5
27+
done'
2128
sudo apt-get install -y postgresql-client-14
2229
fi
2330

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ test: manifests generate fmt vet envtest ## Run tests.
7070
.PHONY: test-e2e # Run the e2e tests against a Kind k8s instance that is spun up.
7171
test-e2e: NS?=$(shell cat .id)
7272
test-e2e:
73-
NAMESPACE=$(NS) go test ./test/e2e/ -v -ginkgo.v
73+
NAMESPACE=$(NS) ENV=box-3 go test ./test/e2e/ -v -ginkgo.v
7474

7575
.PHONY: lint
7676
lint: golangci-lint ## Run golangci-lint linter

Makefile.infoblox

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ push-images: docker-push-db-controller docker-push-dbproxy docker-push-dsnexec
9393
${HELM_SETFLAGS}
9494
# Consider removing this, since we dont actually no
9595
# helm upgrade is applied in the cluster
96-
@touch $@
96+
#@touch $@
9797

9898
deploy: package-chart-db-controller .deploy-$(GIT_COMMIT)
9999

cmd/config/config.yaml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,12 @@ passwordConfig:
3131
minPasswordLength: 15
3232
passwordRotationPeriod: 60
3333
sample-connection:
34-
masterUsername: root
34+
masterUsername: postgres
3535
username: postgres
3636
host: localhost
3737
port: 5432
3838
sslMode: disable
3939
passwordSecretRef: postgres-postgresql
40-
passwordSecretKey: postgresql-password
4140
# host omitted, allocates database dynamically
4241
dynamic-connection:
4342
masterUsername: root

cmd/main.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,13 @@ func main() {
189189
}
190190

191191
dbClaimConfig := &databaseclaim.DatabaseClaimConfig{
192-
Viper: ctlConfig,
193-
192+
Viper: ctlConfig,
193+
Namespace: os.Getenv("SERVICE_NAMESPACE"),
194194
Class: class,
195195
DbIdentifierPrefix: dbIdentifierPrefix,
196196
// Log: ctrl.Log.WithName("controllers").WithName("DatabaseClaim").V(controllers.InfoLevel),
197197
MasterAuth: rdsauth.NewMasterAuth(),
198+
MetricsEnabled: true,
198199
MetricsDepYamlPath: metricsDepYamlPath,
199200
MetricsConfigYamlPath: metricsConfigYamlPath,
200201
}

internal/controller/databaseclaim_controller.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,17 @@ func (r *DatabaseClaimReconciler) Reconcile(ctx context.Context, req ctrl.Reques
6262
return r.reconciler.Reconcile(ctx, req)
6363
}
6464

65-
// SetupWithManager sets up the controller with the Manager.
66-
func (r *DatabaseClaimReconciler) SetupWithManager(mgr ctrl.Manager) error {
67-
65+
func (r *DatabaseClaimReconciler) Setup() {
6866
r.reconciler = &databaseclaim.DatabaseClaimReconciler{
6967
Client: r.Client,
7068
Config: r.Config,
7169
}
70+
}
71+
72+
// SetupWithManager sets up the controller with the Manager.
73+
func (r *DatabaseClaimReconciler) SetupWithManager(mgr ctrl.Manager) error {
74+
75+
r.Setup()
7276

7377
return ctrl.NewControllerManagedBy(mgr).
7478
For(&persistancev1.DatabaseClaim{}).

internal/controller/databaseclaim_controller_test.go

Lines changed: 163 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,25 @@ limitations under the License.
1717
package controller
1818

1919
import (
20+
"context"
21+
"net/url"
22+
"path/filepath"
23+
"testing"
24+
"time"
25+
2026
. "github.com/onsi/ginkgo/v2"
21-
//. "github.com/onsi/gomega"
27+
. "github.com/onsi/gomega"
28+
29+
corev1 "k8s.io/api/core/v1"
30+
"k8s.io/apimachinery/pkg/api/errors"
31+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32+
"k8s.io/apimachinery/pkg/types"
33+
"k8s.io/utils/ptr"
34+
"sigs.k8s.io/controller-runtime/pkg/reconcile"
35+
36+
persistancev1 "github.com/infobloxopen/db-controller/api/v1"
37+
"github.com/infobloxopen/db-controller/pkg/config"
38+
"github.com/infobloxopen/db-controller/pkg/databaseclaim"
2239
)
2340

2441
var _ = Describe("DatabaseClaim Controller", func() {
@@ -78,3 +95,148 @@ var _ = Describe("DatabaseClaim Controller", func() {
7895
})
7996

8097
})
98+
99+
var _ = Describe("db-controller", func() {
100+
101+
// Define utility constants for object names and testing timeouts/durations and intervals.
102+
103+
Context("When updating DB Claim Status", func() {
104+
105+
const resourceName = "test-dbclaim"
106+
const secretName = "postgres-postgresql"
107+
108+
ctx := context.Background()
109+
typeNamespacedName := types.NamespacedName{
110+
Name: resourceName,
111+
Namespace: "default", // TODO(user):Modify as needed
112+
}
113+
typeNamespacedSecretName := types.NamespacedName{
114+
Name: secretName,
115+
Namespace: "default", // TODO(user):Modify as needed
116+
}
117+
claim := &persistancev1.DatabaseClaim{}
118+
119+
BeforeEach(func() {
120+
parsedDSN, err := url.Parse(testDSN)
121+
Expect(err).NotTo(HaveOccurred())
122+
password, ok := parsedDSN.User.Password()
123+
Expect(ok).To(BeTrue())
124+
125+
By("creating the custom resource for the Kind DatabaseClaim")
126+
err = k8sClient.Get(ctx, typeNamespacedName, claim)
127+
if err != nil && errors.IsNotFound(err) {
128+
resource := &persistancev1.DatabaseClaim{
129+
TypeMeta: metav1.TypeMeta{
130+
APIVersion: "persistance.atlas.infoblox.com/v1",
131+
Kind: "DatabaseClaim",
132+
},
133+
ObjectMeta: metav1.ObjectMeta{
134+
Name: resourceName,
135+
Namespace: "default",
136+
},
137+
Spec: persistancev1.DatabaseClaimSpec{
138+
Class: ptr.To(""),
139+
AppID: "sample-app",
140+
DatabaseName: "sample_app",
141+
InstanceLabel: "sample-connection",
142+
SecretName: secretName,
143+
Username: parsedDSN.User.Username(),
144+
EnableSuperUser: ptr.To(false),
145+
EnableReplicationRole: ptr.To(false),
146+
UseExistingSource: ptr.To(false),
147+
Type: "postgres",
148+
149+
Port: parsedDSN.Port(),
150+
Host: parsedDSN.Hostname(),
151+
},
152+
}
153+
Expect(k8sClient.Create(ctx, resource)).To(Succeed())
154+
}
155+
156+
secret := &corev1.Secret{}
157+
err = k8sClient.Get(ctx, typeNamespacedSecretName, secret)
158+
if err != nil && errors.IsNotFound(err) {
159+
resource := &corev1.Secret{
160+
ObjectMeta: metav1.ObjectMeta{
161+
Name: secretName,
162+
Namespace: "default",
163+
},
164+
StringData: map[string]string{
165+
"password": password,
166+
},
167+
Type: "Opaque",
168+
}
169+
Expect(k8sClient.Create(ctx, resource)).To(Succeed())
170+
171+
}
172+
173+
})
174+
175+
AfterEach(func() {
176+
// TODO(user): Cleanup logic after each test, like removing the resource instance.
177+
resource := &persistancev1.DatabaseClaim{}
178+
err := k8sClient.Get(ctx, typeNamespacedName, resource)
179+
Expect(err).NotTo(HaveOccurred())
180+
181+
By("Cleanup the specific resource instance DatabaseClaim")
182+
Expect(k8sClient.Delete(ctx, resource)).To(Succeed())
183+
184+
secret := &corev1.Secret{}
185+
err = k8sClient.Get(ctx, typeNamespacedSecretName, secret)
186+
Expect(err).NotTo(HaveOccurred())
187+
188+
By("Cleanup the database secret")
189+
190+
Expect(k8sClient.Delete(ctx, secret)).To(Succeed())
191+
192+
})
193+
194+
It("Should update DB Claim status", func() {
195+
196+
By("Reconciling the created resource")
197+
198+
configPath, err := filepath.Abs(filepath.Join("..", "..", "cmd", "config", "config.yaml"))
199+
Expect(err).NotTo(HaveOccurred())
200+
201+
controllerReconciler := &DatabaseClaimReconciler{
202+
Config: &databaseclaim.DatabaseClaimConfig{
203+
Viper: config.NewConfig(logger, configPath),
204+
Namespace: "default",
205+
},
206+
Client: k8sClient,
207+
Scheme: k8sClient.Scheme(),
208+
}
209+
controllerReconciler.Setup()
210+
211+
// FIXME: make these actual properties on the reconciler struct
212+
controllerReconciler.Config.Viper.Set("defaultMasterusername", "postgres")
213+
controllerReconciler.Config.Viper.Set("defaultSslMode", "require")
214+
215+
_, err = controllerReconciler.Reconcile(ctx, reconcile.Request{
216+
NamespacedName: typeNamespacedName,
217+
})
218+
Expect(err).NotTo(HaveOccurred())
219+
220+
Eventually(func() bool {
221+
resource := &persistancev1.DatabaseClaim{}
222+
err := k8sClient.Get(ctx, typeNamespacedName, resource)
223+
if err != nil {
224+
return false
225+
}
226+
return resource.Status.Error == ""
227+
228+
}, 10*time.Second, 100*time.Millisecond).Should(BeTrue())
229+
230+
})
231+
})
232+
})
233+
234+
func TestDB(t *testing.T) {
235+
db, _, cleanup := RunDB()
236+
defer cleanup()
237+
defer db.Close()
238+
_, err := db.Exec("CREATE TABLE test (id SERIAL PRIMARY KEY, name TEXT)")
239+
if err != nil {
240+
panic(err)
241+
}
242+
}

internal/controller/dbroleclaim_controller_test.go

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ func TestReconcileDbRoleClaim_CopyExistingSecret(t *testing.T) {
5353
Name: resourceName,
5454
Namespace: "default",
5555
}
56+
typeNamespacedClaimName := types.NamespacedName{
57+
Name: "testdbclaim",
58+
Namespace: "default",
59+
}
60+
typeNamespacedSecretName := types.NamespacedName{
61+
Name: "master-secret",
62+
Namespace: "default",
63+
}
64+
5665
dbroleclaim := &persistancev1.DbRoleClaim{}
5766
viperObj := viper.New()
5867
viperObj.Set("passwordconfig::passwordRotationPeriod", 60)
@@ -77,7 +86,11 @@ func TestReconcileDbRoleClaim_CopyExistingSecret(t *testing.T) {
7786
Status: persistancev1.DbRoleClaimStatus{},
7887
}
7988
Expect(k8sClient.Create(ctx, resource)).To(Succeed())
89+
}
8090

91+
dbclaim := persistancev1.DatabaseClaim{}
92+
err = k8sClient.Get(ctx, typeNamespacedClaimName, &dbclaim)
93+
if err != nil && errors.IsNotFound(err) {
8194
dbClaim := &persistancev1.DatabaseClaim{
8295
ObjectMeta: metav1.ObjectMeta{
8396
Name: "testdbclaim",
@@ -91,14 +104,22 @@ func TestReconcileDbRoleClaim_CopyExistingSecret(t *testing.T) {
91104
Status: persistancev1.DatabaseClaimStatus{},
92105
}
93106
Expect(k8sClient.Create(ctx, dbClaim)).To(Succeed())
107+
}
108+
109+
secret := corev1.Secret{}
110+
err = k8sClient.Get(ctx, typeNamespacedSecretName, &secret)
111+
if err != nil && errors.IsNotFound(err) {
94112

95-
sec := &corev1.Secret{}
96-
sec.Data = map[string][]byte{
97-
"password": []byte("masterpassword"),
98-
"username": []byte("user_a"),
113+
sec := &corev1.Secret{
114+
ObjectMeta: metav1.ObjectMeta{
115+
Name: "master-secret",
116+
Namespace: "default",
117+
},
118+
Data: map[string][]byte{
119+
"password": []byte("masterpassword"),
120+
"username": []byte("user_a"),
121+
},
99122
}
100-
sec.Name = "master-secret"
101-
sec.Namespace = "default"
102123
Expect(k8sClient.Create(ctx, sec)).To(Succeed())
103124
}
104125
})

internal/controller/suite_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,15 @@ limitations under the License.
1717
package controller
1818

1919
import (
20+
"database/sql"
2021
"fmt"
2122
"path/filepath"
2223
"runtime"
2324
"testing"
25+
"time"
2426

27+
"github.com/go-logr/logr"
28+
"github.com/go-logr/logr/funcr"
2529
. "github.com/onsi/ginkgo/v2"
2630
. "github.com/onsi/gomega"
2731

@@ -42,17 +46,26 @@ import (
4246
var cfg *rest.Config
4347
var k8sClient client.Client
4448
var testEnv *envtest.Environment
49+
var namespace string
50+
var logger logr.Logger
4551

4652
func TestControllers(t *testing.T) {
4753
RegisterFailHandler(Fail)
4854

4955
RunSpecs(t, "Controller Suite")
56+
57+
logger = funcr.New(func(prefix, args string) {
58+
t.Log(prefix, args)
59+
}, funcr.Options{
60+
Verbosity: 1,
61+
})
5062
}
5163

5264
var _ = BeforeSuite(func() {
5365
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))
5466

5567
By("bootstrapping test environment")
68+
namespace = "default"
5669
testEnv = &envtest.Environment{
5770
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")},
5871
ErrorIfCRDPathMissing: true,
@@ -81,9 +94,21 @@ var _ = BeforeSuite(func() {
8194
Expect(err).NotTo(HaveOccurred())
8295
Expect(k8sClient).NotTo(BeNil())
8396

97+
now := time.Now()
98+
testdb, testDSN, cleanupTestDB = RunDB()
99+
logger.Info("postgres_setup_took", "duration", time.Since(now))
100+
84101
})
85102

103+
// Stand up postgres in a container
104+
var (
105+
testdb *sql.DB
106+
testDSN string
107+
cleanupTestDB func()
108+
)
109+
86110
var _ = AfterSuite(func() {
111+
cleanupTestDB()
87112
By("tearing down the test environment")
88113
err := testEnv.Stop()
89114
Expect(err).NotTo(HaveOccurred())

0 commit comments

Comments
 (0)