/
postgres.go
254 lines (223 loc) · 5.26 KB
/
postgres.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package itest
import (
"context"
"encoding/binary"
"fmt"
"io"
"log"
"os"
"strconv"
"sync"
"time"
"github.com/breez/lntest"
"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/jackc/pgx/v5/pgxpool"
)
type PostgresContainer struct {
id string
password string
port uint32
cli *client.Client
logfile string
isInitialized bool
isStarted bool
pool *pgxpool.Pool
mtx sync.Mutex
}
func (p *PostgresContainer) Pool() *pgxpool.Pool {
return p.pool
}
func NewPostgresContainer(logfile string) (*PostgresContainer, error) {
port, err := lntest.GetPort()
if err != nil {
return nil, fmt.Errorf("could not get port: %w", err)
}
return &PostgresContainer{
password: "pgpassword",
port: port,
logfile: logfile,
}, nil
}
func (c *PostgresContainer) Start(ctx context.Context) error {
c.mtx.Lock()
defer c.mtx.Unlock()
var err error
if c.isStarted {
return nil
}
c.cli, err = client.NewClientWithOpts(client.FromEnv)
if err != nil {
return fmt.Errorf("could not create docker client: %w", err)
}
if !c.isInitialized {
err := c.initialize(ctx)
if err != nil {
c.cli.Close()
return err
}
}
err = c.cli.ContainerStart(ctx, c.id, types.ContainerStartOptions{})
if err != nil {
c.cli.Close()
return fmt.Errorf("failed to start docker container '%s': %w", c.id, err)
}
c.isStarted = true
HealthCheck:
for {
inspect, err := c.cli.ContainerInspect(ctx, c.id)
if err != nil {
c.cli.ContainerStop(ctx, c.id, container.StopOptions{})
c.cli.Close()
return fmt.Errorf("failed to inspect container '%s' during healthcheck: %w", c.id, err)
}
status := inspect.State.Health.Status
switch status {
case "unhealthy":
c.cli.ContainerStop(ctx, c.id, container.StopOptions{})
c.cli.Close()
return fmt.Errorf("container '%s' unhealthy", c.id)
case "healthy":
for {
if c.pool == nil {
c.pool, err = pgxpool.New(ctx, c.ConnectionString())
if err != nil {
<-time.After(50 * time.Millisecond)
continue
}
}
_, err = c.pool.Exec(ctx, "SELECT 1;")
if err == nil {
break HealthCheck
}
<-time.After(50 * time.Millisecond)
}
default:
<-time.After(200 * time.Millisecond)
}
}
go c.monitorLogs(ctx)
return nil
}
func (c *PostgresContainer) initialize(ctx context.Context) error {
image := "postgres:15"
_, _, err := c.cli.ImageInspectWithRaw(ctx, image)
if err != nil {
if !client.IsErrNotFound(err) {
return fmt.Errorf("could not find docker image '%s': %w", image, err)
}
pullReader, err := c.cli.ImagePull(ctx, image, types.ImagePullOptions{})
if err != nil {
return fmt.Errorf("failed to pull docker image '%s': %w", image, err)
}
defer pullReader.Close()
_, err = io.Copy(io.Discard, pullReader)
if err != nil {
return fmt.Errorf("failed to download docker image '%s': %w", image, err)
}
}
createResp, err := c.cli.ContainerCreate(ctx, &container.Config{
Image: image,
Cmd: []string{
"postgres",
"-c",
"log_statement=all",
},
Env: []string{
"POSTGRES_DB=postgres",
"POSTGRES_PASSWORD=pgpassword",
"POSTGRES_USER=postgres",
},
Healthcheck: &container.HealthConfig{
Test: []string{"CMD-SHELL", "pg_isready -U postgres"},
Interval: time.Second,
Timeout: time.Second,
Retries: 10,
},
}, &container.HostConfig{
PortBindings: nat.PortMap{
"5432/tcp": []nat.PortBinding{
{HostPort: strconv.FormatUint(uint64(c.port), 10)},
},
},
},
nil,
nil,
"",
)
if err != nil {
return fmt.Errorf("failed to create docker container: %w", err)
}
c.id = createResp.ID
c.isInitialized = true
return nil
}
func (c *PostgresContainer) Stop(ctx context.Context) error {
c.mtx.Lock()
defer c.mtx.Unlock()
if !c.isStarted {
return nil
}
if c.pool != nil {
c.pool.Close()
c.pool = nil
}
defer c.cli.Close()
err := c.cli.ContainerStop(ctx, c.id, container.StopOptions{})
c.isStarted = false
return err
}
func (c *PostgresContainer) Cleanup(ctx context.Context) error {
c.mtx.Lock()
defer c.mtx.Unlock()
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return err
}
defer cli.Close()
return cli.ContainerRemove(ctx, c.id, types.ContainerRemoveOptions{
Force: true,
})
}
func (c *PostgresContainer) monitorLogs(ctx context.Context) {
i, err := c.cli.ContainerLogs(ctx, c.id, types.ContainerLogsOptions{
ShowStderr: true,
ShowStdout: true,
Timestamps: false,
Follow: true,
Tail: "40",
})
if err != nil {
log.Printf("Could not get container logs: %v", err)
return
}
defer i.Close()
file, err := os.Create(c.logfile)
if err != nil {
log.Printf("Could not create container log file %v: %v", c.logfile, err)
return
}
defer file.Close()
hdr := make([]byte, 8)
for {
_, err := i.Read(hdr)
if err != nil {
return
}
count := binary.BigEndian.Uint32(hdr[4:])
dat := make([]byte, count)
_, err = i.Read(dat)
if err != nil {
return
}
_, err = file.Write(dat)
if err != nil {
return
}
}
}
func (c *PostgresContainer) ConnectionString() string {
return fmt.Sprintf("postgres://postgres:%s@127.0.0.1:%d/postgres?sslmode=disable", c.password, c.port)
}