Skip to content

Commit f7858ff

Browse files
authored
Initialize arrays of errors / error messages + minor refactoring (zalando#1701)
* init error arrays correctly * avoid nilPointer when syncing connectionPooler * getInfrastructureRoles should return error * fix unit tests and return type for getInfrastructureRoles
1 parent 3e275d1 commit f7858ff

File tree

7 files changed

+38
-76
lines changed

7 files changed

+38
-76
lines changed

pkg/cluster/connection_pooler.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -712,7 +712,8 @@ func (c *Cluster) syncConnectionPooler(oldSpec, newSpec *acidv1.Postgresql, Look
712712
if (!needSync && len(masterChanges) <= 0 && len(replicaChanges) <= 0) &&
713713
((!needConnectionPooler(&newSpec.Spec) && (c.ConnectionPooler == nil || !needConnectionPooler(&oldSpec.Spec))) ||
714714
(c.ConnectionPooler != nil && needConnectionPooler(&newSpec.Spec) &&
715-
(c.ConnectionPooler[Master].LookupFunction || c.ConnectionPooler[Replica].LookupFunction))) {
715+
((c.ConnectionPooler[Master] != nil && c.ConnectionPooler[Master].LookupFunction) ||
716+
(c.ConnectionPooler[Replica] != nil && c.ConnectionPooler[Replica].LookupFunction)))) {
716717
c.logger.Debugln("syncing pooler is not required")
717718
return nil, nil
718719
}

pkg/cluster/resources.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -496,18 +496,17 @@ func (c *Cluster) deleteEndpoint(role PostgresRole) error {
496496

497497
func (c *Cluster) deleteSecrets() error {
498498
c.setProcessName("deleting secrets")
499-
var errors []string
500-
errorCount := 0
499+
errors := make([]string, 0)
500+
501501
for uid, secret := range c.Secrets {
502502
err := c.deleteSecret(uid, *secret)
503503
if err != nil {
504504
errors = append(errors, fmt.Sprintf("%v", err))
505-
errorCount++
506505
}
507506
}
508507

509-
if errorCount > 0 {
510-
return fmt.Errorf("could not delete all secrets: %v", errors)
508+
if len(errors) > 0 {
509+
return fmt.Errorf("could not delete all secrets: %v", strings.Join(errors, `', '`))
511510
}
512511

513512
return nil

pkg/cluster/sync_test.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -196,17 +196,15 @@ func TestCheckAndSetGlobalPostgreSQLConfiguration(t *testing.T) {
196196
cluster.patroni = p
197197
mockPod := newMockPod("192.168.100.1")
198198

199-
// simulate existing config that differs with cluster.Spec
199+
// simulate existing config that differs from cluster.Spec
200200
tests := []struct {
201201
subtest string
202-
pod *v1.Pod
203202
patroni acidv1.Patroni
204203
pgParams map[string]string
205204
restartMaster bool
206205
}{
207206
{
208207
subtest: "Patroni and Postgresql.Parameters differ - restart replica first",
209-
pod: mockPod,
210208
patroni: acidv1.Patroni{
211209
TTL: 30, // desired 20
212210
},
@@ -218,7 +216,6 @@ func TestCheckAndSetGlobalPostgreSQLConfiguration(t *testing.T) {
218216
},
219217
{
220218
subtest: "multiple Postgresql.Parameters differ - restart replica first",
221-
pod: mockPod,
222219
patroni: acidv1.Patroni{
223220
TTL: 20,
224221
},
@@ -230,7 +227,6 @@ func TestCheckAndSetGlobalPostgreSQLConfiguration(t *testing.T) {
230227
},
231228
{
232229
subtest: "desired max_connections bigger - restart replica first",
233-
pod: mockPod,
234230
patroni: acidv1.Patroni{
235231
TTL: 20,
236232
},
@@ -242,7 +238,6 @@ func TestCheckAndSetGlobalPostgreSQLConfiguration(t *testing.T) {
242238
},
243239
{
244240
subtest: "desired max_connections smaller - restart master first",
245-
pod: mockPod,
246241
patroni: acidv1.Patroni{
247242
TTL: 20,
248243
},
@@ -255,7 +250,7 @@ func TestCheckAndSetGlobalPostgreSQLConfiguration(t *testing.T) {
255250
}
256251

257252
for _, tt := range tests {
258-
requireMasterRestart, err := cluster.checkAndSetGlobalPostgreSQLConfiguration(tt.pod, tt.patroni, tt.pgParams)
253+
requireMasterRestart, err := cluster.checkAndSetGlobalPostgreSQLConfiguration(mockPod, tt.patroni, tt.pgParams)
259254
assert.NoError(t, err)
260255
if requireMasterRestart != tt.restartMaster {
261256
t.Errorf("%s - %s: unexpect master restart strategy, got %v, expected %v", testName, tt.subtest, requireMasterRestart, tt.restartMaster)

pkg/cluster/volumes.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ func (c *Cluster) syncUnderlyingEBSVolume() error {
8888
awsGp3 := aws.String("gp3")
8989
awsIo2 := aws.String("io2")
9090

91-
errors := []string{}
91+
errors := make([]string, 0)
9292

9393
for _, volume := range c.EBSVolumes {
9494
var modifyIops *int64

pkg/controller/util.go

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -195,13 +195,12 @@ func (c *Controller) getInfrastructureRoleDefinitions() []*config.Infrastructure
195195

196196
func (c *Controller) getInfrastructureRoles(
197197
rolesSecrets []*config.InfrastructureRole) (
198-
map[string]spec.PgUser, []error) {
199-
200-
var errors []error
201-
var noRolesProvided = true
198+
map[string]spec.PgUser, error) {
202199

200+
errors := make([]string, 0)
201+
noRolesProvided := true
203202
roles := []spec.PgUser{}
204-
uniqRoles := map[string]spec.PgUser{}
203+
uniqRoles := make(map[string]spec.PgUser)
205204

206205
// To be compatible with the legacy implementation we need to return nil if
207206
// the provided secret name is empty. The equivalent situation in the
@@ -214,37 +213,39 @@ func (c *Controller) getInfrastructureRoles(
214213
}
215214

216215
if noRolesProvided {
217-
return nil, nil
216+
return uniqRoles, nil
218217
}
219218

220219
for _, secret := range rolesSecrets {
221220
infraRoles, err := c.getInfrastructureRole(secret)
222221

223222
if err != nil || infraRoles == nil {
224-
c.logger.Debugf("Cannot get infrastructure role: %+v", *secret)
223+
c.logger.Debugf("cannot get infrastructure role: %+v", *secret)
225224

226225
if err != nil {
227-
errors = append(errors, err)
226+
errors = append(errors, fmt.Sprintf("%v", err))
228227
}
229228

230229
continue
231230
}
232231

233-
for _, r := range infraRoles {
234-
roles = append(roles, r)
235-
}
232+
roles = append(roles, infraRoles...)
236233
}
237234

238235
for _, r := range roles {
239236
if _, exists := uniqRoles[r.Name]; exists {
240-
msg := "Conflicting infrastructure roles: roles[%s] = (%q, %q)"
237+
msg := "conflicting infrastructure roles: roles[%s] = (%q, %q)"
241238
c.logger.Debugf(msg, r.Name, uniqRoles[r.Name], r)
242239
}
243240

244241
uniqRoles[r.Name] = r
245242
}
246243

247-
return uniqRoles, errors
244+
if len(errors) > 0 {
245+
return uniqRoles, fmt.Errorf(strings.Join(errors, `', '`))
246+
}
247+
248+
return uniqRoles, nil
248249
}
249250

250251
// Generate list of users representing one infrastructure role based on its

pkg/controller/util_test.go

Lines changed: 13 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
b64 "encoding/base64"
99

10+
"github.com/stretchr/testify/assert"
1011
"github.com/zalando/postgres-operator/pkg/spec"
1112
"github.com/zalando/postgres-operator/pkg/util/config"
1213
"github.com/zalando/postgres-operator/pkg/util/k8sutil"
@@ -90,21 +91,21 @@ func TestClusterWorkerID(t *testing.T) {
9091
// not exist, or empty) and the old format.
9192
func TestOldInfrastructureRoleFormat(t *testing.T) {
9293
var testTable = []struct {
93-
secretName spec.NamespacedName
94-
expectedRoles map[string]spec.PgUser
95-
expectedErrors []error
94+
secretName spec.NamespacedName
95+
expectedRoles map[string]spec.PgUser
96+
expectedError error
9697
}{
9798
{
9899
// empty secret name
99100
spec.NamespacedName{},
100-
nil,
101+
map[string]spec.PgUser{},
101102
nil,
102103
},
103104
{
104105
// secret does not exist
105106
spec.NamespacedName{Namespace: v1.NamespaceDefault, Name: "null"},
106107
map[string]spec.PgUser{},
107-
[]error{fmt.Errorf(`could not get infrastructure roles secret default/null: NotFound`)},
108+
fmt.Errorf(`could not get infrastructure roles secret default/null: NotFound`),
108109
},
109110
{
110111
spec.NamespacedName{
@@ -129,7 +130,7 @@ func TestOldInfrastructureRoleFormat(t *testing.T) {
129130
},
130131
}
131132
for _, test := range testTable {
132-
roles, errors := utilTestController.getInfrastructureRoles(
133+
roles, err := utilTestController.getInfrastructureRoles(
133134
[]*config.InfrastructureRole{
134135
&config.InfrastructureRole{
135136
SecretName: test.secretName,
@@ -140,22 +141,9 @@ func TestOldInfrastructureRoleFormat(t *testing.T) {
140141
},
141142
})
142143

143-
if len(errors) != len(test.expectedErrors) {
144+
if err != nil && err.Error() != test.expectedError.Error() {
144145
t.Errorf("expected error '%v' does not match the actual error '%v'",
145-
test.expectedErrors, errors)
146-
}
147-
148-
for idx := range errors {
149-
err := errors[idx]
150-
expectedErr := test.expectedErrors[idx]
151-
152-
if err != expectedErr {
153-
if err != nil && expectedErr != nil && err.Error() == expectedErr.Error() {
154-
continue
155-
}
156-
t.Errorf("expected error '%v' does not match the actual error '%v'",
157-
expectedErr, err)
158-
}
146+
test.expectedError, err)
159147
}
160148

161149
if !reflect.DeepEqual(roles, test.expectedRoles) {
@@ -169,9 +157,8 @@ func TestOldInfrastructureRoleFormat(t *testing.T) {
169157
// corresponding secrets. Here we test the new format.
170158
func TestNewInfrastructureRoleFormat(t *testing.T) {
171159
var testTable = []struct {
172-
secrets []spec.NamespacedName
173-
expectedRoles map[string]spec.PgUser
174-
expectedErrors []error
160+
secrets []spec.NamespacedName
161+
expectedRoles map[string]spec.PgUser
175162
}{
176163
// one secret with one configmap
177164
{
@@ -196,7 +183,6 @@ func TestNewInfrastructureRoleFormat(t *testing.T) {
196183
Flags: []string{"createdb"},
197184
},
198185
},
199-
nil,
200186
},
201187
// multiple standalone secrets
202188
{
@@ -224,7 +210,6 @@ func TestNewInfrastructureRoleFormat(t *testing.T) {
224210
MemberOf: []string{"new-test-inrole2"},
225211
},
226212
},
227-
nil,
228213
},
229214
}
230215
for _, test := range testTable {
@@ -239,27 +224,8 @@ func TestNewInfrastructureRoleFormat(t *testing.T) {
239224
})
240225
}
241226

242-
roles, errors := utilTestController.getInfrastructureRoles(definitions)
243-
if len(errors) != len(test.expectedErrors) {
244-
t.Errorf("expected error does not match the actual error:\n%+v\n%+v",
245-
test.expectedErrors, errors)
246-
247-
// Stop and do not do any further checks
248-
return
249-
}
250-
251-
for idx := range errors {
252-
err := errors[idx]
253-
expectedErr := test.expectedErrors[idx]
254-
255-
if err != expectedErr {
256-
if err != nil && expectedErr != nil && err.Error() == expectedErr.Error() {
257-
continue
258-
}
259-
t.Errorf("expected error '%v' does not match the actual error '%v'",
260-
expectedErr, err)
261-
}
262-
}
227+
roles, err := utilTestController.getInfrastructureRoles(definitions)
228+
assert.NoError(t, err)
263229

264230
if !reflect.DeepEqual(roles, test.expectedRoles) {
265231
t.Errorf("expected roles output/the actual:\n%#v\n%#v",

pkg/util/users/users.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ func (strategy DefaultUserSyncStrategy) ProduceSyncRequests(dbUsers spec.PgUserM
101101
// ExecuteSyncRequests makes actual database changes from the requests passed in its arguments.
102102
func (strategy DefaultUserSyncStrategy) ExecuteSyncRequests(requests []spec.PgSyncUserRequest, db *sql.DB) error {
103103
var reqretries []spec.PgSyncUserRequest
104-
var errors []string
104+
errors := make([]string, 0)
105105
for _, request := range requests {
106106
switch request.Kind {
107107
case spec.PGSyncUserAdd:
@@ -138,7 +138,7 @@ func (strategy DefaultUserSyncStrategy) ExecuteSyncRequests(requests []spec.PgSy
138138
return err
139139
}
140140
} else {
141-
return fmt.Errorf("could not execute sync requests for users: %v", errors)
141+
return fmt.Errorf("could not execute sync requests for users: %v", strings.Join(errors, `', '`))
142142
}
143143
}
144144

0 commit comments

Comments
 (0)