-
Notifications
You must be signed in to change notification settings - Fork 171
/
mysql.go
208 lines (169 loc) · 5.19 KB
/
mysql.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
package storage
import (
"context"
"fmt"
"io"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/go-sql-driver/mysql"
"github.com/oklog/ulid/v2"
"github.com/openfga/openfga/assets"
"github.com/pressly/goose/v3"
"github.com/stretchr/testify/require"
)
const (
mySQLImage = "mysql:8"
)
type mySQLTestContainer struct {
addr string
version int64
username string
password string
}
// NewMySQLTestContainer returns an implementation of the DatastoreTestContainer interface
// for MySQL.
func NewMySQLTestContainer() *mySQLTestContainer {
return &mySQLTestContainer{}
}
func (m *mySQLTestContainer) GetDatabaseSchemaVersion() int64 {
return m.version
}
// RunMySQLTestContainer runs a MySQL container, connects to it, and returns a
// bootstrapped implementation of the DatastoreTestContainer interface wired up for the
// MySQL datastore engine.
func (m *mySQLTestContainer) RunMySQLTestContainer(t testing.TB) DatastoreTestContainer {
dockerClient, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
require.NoError(t, err)
allImages, err := dockerClient.ImageList(context.Background(), types.ImageListOptions{
All: true,
})
require.NoError(t, err)
foundMysqlImage := false
for _, image := range allImages {
for _, tag := range image.RepoTags {
if strings.Contains(tag, mySQLImage) {
foundMysqlImage = true
break
}
}
}
if !foundMysqlImage {
t.Logf("Pulling image %s", mySQLImage)
reader, err := dockerClient.ImagePull(context.Background(), mySQLImage, types.ImagePullOptions{})
require.NoError(t, err)
_, err = io.Copy(io.Discard, reader) // consume the image pull output to make sure it's done
require.NoError(t, err)
}
containerCfg := container.Config{
Env: []string{
"MYSQL_DATABASE=defaultdb",
"MYSQL_ROOT_PASSWORD=secret",
},
ExposedPorts: nat.PortSet{
nat.Port("3306/tcp"): {},
},
Image: mySQLImage,
}
hostCfg := container.HostConfig{
AutoRemove: true,
PublishAllPorts: true,
}
name := fmt.Sprintf("mysql-%s", ulid.Make().String())
cont, err := dockerClient.ContainerCreate(context.Background(), &containerCfg, &hostCfg, nil, nil, name)
require.NoError(t, err, "failed to create mysql docker container")
stopContainer := func() {
t.Logf("stopping container %s", name)
timeoutSec := 5
err := dockerClient.ContainerStop(context.Background(), cont.ID, container.StopOptions{Timeout: &timeoutSec})
if err != nil && !client.IsErrNotFound(err) {
t.Logf("failed to stop mysql container: %v", err)
}
dockerClient.Close()
t.Logf("stopped container %s", name)
}
err = dockerClient.ContainerStart(context.Background(), cont.ID, types.ContainerStartOptions{})
if err != nil {
stopContainer()
t.Fatalf("failed to start mysql container: %v", err)
}
containerJSON, err := dockerClient.ContainerInspect(context.Background(), cont.ID)
require.NoError(t, err)
p, ok := containerJSON.NetworkSettings.Ports["3306/tcp"]
if !ok || len(p) == 0 {
t.Fatalf("failed to get host port mapping from mysql container")
}
// spin up a goroutine to survive any test panics to expire/stop the running container
go func() {
time.Sleep(expireTimeout)
timeoutSec := 0
t.Logf("expiring container %s", name)
err := dockerClient.ContainerStop(context.Background(), cont.ID, container.StopOptions{Timeout: &timeoutSec})
if err != nil && !client.IsErrNotFound(err) {
t.Logf("failed to expire mysql container: %v", err)
}
t.Logf("expired container %s", name)
}()
t.Cleanup(func() {
stopContainer()
})
mySQLTestContainer := &mySQLTestContainer{
addr: fmt.Sprintf("localhost:%s", p[0].HostPort),
username: "root",
password: "secret",
}
uri := fmt.Sprintf("%s:%s@tcp(%s)/defaultdb?parseTime=true", mySQLTestContainer.username, mySQLTestContainer.password, mySQLTestContainer.addr)
err = mysql.SetLogger(goose.NopLogger())
require.NoError(t, err)
goose.SetLogger(goose.NopLogger())
db, err := goose.OpenDBWithDriver("mysql", uri)
require.NoError(t, err)
backoffPolicy := backoff.NewExponentialBackOff()
backoffPolicy.MaxElapsedTime = time.Minute
err = backoff.Retry(
func() error {
return db.Ping()
},
backoffPolicy,
)
if err != nil {
stopContainer()
t.Fatalf("failed to connect to mysql container: %v", err)
}
goose.SetBaseFS(assets.EmbedMigrations)
err = goose.Up(db, assets.MySQLMigrationDir)
require.NoError(t, err)
version, err := goose.GetDBVersion(db)
require.NoError(t, err)
mySQLTestContainer.version = version
err = db.Close()
require.NoError(t, err)
return mySQLTestContainer
}
// GetConnectionURI returns the mysql connection uri for the running mysql test container.
func (m *mySQLTestContainer) GetConnectionURI(includeCredentials bool) string {
creds := ""
if includeCredentials {
creds = fmt.Sprintf("%s:%s@", m.username, m.password)
}
return fmt.Sprintf(
"%stcp(%s)/%s?parseTime=true",
creds,
m.addr,
"defaultdb",
)
}
func (m *mySQLTestContainer) GetUsername() string {
return m.username
}
func (m *mySQLTestContainer) GetPassword() string {
return m.password
}