-
Notifications
You must be signed in to change notification settings - Fork 113
/
database.go
225 lines (169 loc) · 5.52 KB
/
database.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
package testutils
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/gocraft/dbr/v2"
"github.com/lib/pq"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
testcontainers "github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
const (
DbUser = "admin"
DbPass = "nimda"
DbName = "provisioner"
DbPort = "5432"
TableCluster = "cluster"
TableGardenerConfig = "gardener_config"
TableOperation = "kyma_config"
TableKymaComponentConfig = "kyma_component_config"
TableRuntimeUpgrade = "runtime_upgrade"
ClusterTableName = "cluster"
SchemaName = "public"
DockerUserNetwork = "test_network"
EnvPipelineBuild = "PIPELINE_BUILD"
TableNotExistsError = "42P01"
connStringFormat = "host=%s port=%s user=%s password=%s dbname=%s sslmode=%s"
)
var (
SchemaFilePath = os.Getenv("GOPATH") + "/src/github.com/kyma-project/control-plane/components/provisioner/assets/database/provisioner.sql"
)
func makeConnectionString(hostname string, port string) string {
return fmt.Sprintf(connStringFormat, hostname, port, DbUser,
DbPass, DbName, "disable")
}
func CloseDatabase(t *testing.T, connection *dbr.Connection) {
if connection != nil {
err := connection.Close()
assert.Nil(t, err, "Failed to close db connection")
}
}
func InitTestDBContainer(t *testing.T, ctx context.Context) (func(), string, error) {
_, err := isDockerTestNetworkPresent(ctx)
if err != nil {
return nil, "", err
}
req := testcontainers.ContainerRequest{
Image: "postgres:11",
SkipReaper: true,
Env: map[string]string{
"POSTGRES_USER": DbUser,
"POSTGRES_PASSWORD": DbPass,
"POSTGRES_DB": DbName,
},
WaitingFor: wait.ForListeningPort(DbPort),
}
postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Logf("Failed to create container: %s", err.Error())
return nil, "", err
}
port, err := postgresContainer.MappedPort(ctx, DbPort)
if err != nil {
t.Logf("Failed to get mapped port for container %s : %s", postgresContainer.GetContainerID(), err.Error())
errTerminate := postgresContainer.Terminate(ctx)
if errTerminate != nil {
t.Logf("Failed to terminate container %s after failing of getting mapped port: %s", postgresContainer.GetContainerID(), err.Error())
}
return nil, "", err
}
ip, err := postgresContainer.Host(ctx)
if err != nil {
t.Logf("Failed to get ip for container %s : %s", postgresContainer.GetContainerID(), err.Error())
errTerminate := postgresContainer.Terminate(ctx)
if errTerminate != nil {
t.Logf("Failed to terminate container %s after failing to get ip: %s", postgresContainer.GetContainerID(), err.Error())
}
return nil, "", err
}
cleanupFunc := func() {
err := postgresContainer.Terminate(ctx)
assert.NoError(t, err)
time.Sleep(2 * time.Second)
}
connString := makeConnectionString(ip, port.Port())
return cleanupFunc, connString, nil
}
func CheckIfAllDatabaseTablesArePresent(db *dbr.Connection) error {
tables := []string{TableCluster, TableGardenerConfig, TableOperation, TableKymaComponentConfig, TableRuntimeUpgrade}
for _, table := range tables {
checkError := checkIfDBTableIsPresent(table, db)
if checkError != nil {
return checkError
}
}
return nil
}
func checkIfDBTableIsPresent(tableNameToCheck string, db *dbr.Connection) error {
checkQuery := fmt.Sprintf(`SELECT '%s.%s'::regclass;`, SchemaName, tableNameToCheck)
row := db.QueryRow(checkQuery)
var tableName string
err := row.Scan(&tableName)
if err != nil {
psqlErr, converted := err.(*pq.Error)
if converted && psqlErr.Code == TableNotExistsError {
return errors.Wrap(err, "Table is missing in the database")
}
return errors.Wrap(err, "Failed to check if table is present in the database")
}
if tableName != ClusterTableName {
return errors.Wrap(err, "Failed verify table name in the database")
}
return nil
}
func isDockerTestNetworkPresent(ctx context.Context) (bool, error) {
netReq := testcontainers.NetworkRequest{
Name: DockerUserNetwork,
Driver: "bridge",
}
provider, err := testcontainers.NewDockerProvider()
if err != nil || provider == nil {
return false, errors.Wrap(err, "Failed to use Docker provider to access network information")
}
_, err = provider.GetNetwork(ctx, netReq)
if err == nil {
return true, nil
}
return false, nil
}
func createTestNetworkForDB(ctx context.Context) (testcontainers.Network, error) {
netReq := testcontainers.NetworkRequest{
Name: DockerUserNetwork,
Driver: "bridge",
}
provider, err := testcontainers.NewDockerProvider()
if err != nil || provider == nil {
return nil, errors.Wrap(err, "Failed to use Docker provider to access network information")
}
createdNetwork, err := provider.CreateNetwork(ctx, netReq)
if err != nil {
return nil, errors.Wrap(err, "Failed to create docker user network")
}
return createdNetwork, nil
}
func EnsureTestNetworkForDB(t *testing.T, ctx context.Context) (func(), error) {
networkPresent, err := isDockerTestNetworkPresent(ctx)
if networkPresent && err == nil {
return func() {}, nil
}
if os.Getenv(EnvPipelineBuild) != "" {
return func() {}, errors.Errorf("Docker network %s does not exist", DockerUserNetwork)
}
createdNetwork, err := createTestNetworkForDB(ctx)
if err != nil {
return func() {}, err
}
cleanupFunc := func() {
err = createdNetwork.Remove(ctx)
assert.NoError(t, err)
time.Sleep(2 * time.Second)
}
return cleanupFunc, nil
}