-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwait.go
More file actions
368 lines (314 loc) · 10.3 KB
/
wait.go
File metadata and controls
368 lines (314 loc) · 10.3 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package docker
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"regexp"
"strings"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
)
// WaitStrategy defines how to wait for a container to be ready.
type WaitStrategy interface {
// WaitUntilReady blocks until the container is ready or timeout occurs.
WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error
}
// waitForLog waits for a specific log pattern to appear.
type waitForLog struct {
pattern *regexp.Regexp
compileErr error
timeout time.Duration
}
// WaitForLog creates a wait strategy that waits for a log pattern.
// Pattern can be a simple string or regex pattern.
// If the pattern is invalid, WaitUntilReady will return an error instead of panicking.
func WaitForLog(pattern string) *waitForLog {
compiled, err := regexp.Compile(pattern)
return &waitForLog{
pattern: compiled,
compileErr: err,
timeout: 60 * time.Second,
}
}
// WithStartupTimeout sets the timeout for the wait strategy.
func (w *waitForLog) WithStartupTimeout(timeout time.Duration) *waitForLog {
w.timeout = timeout
return w
}
// WaitUntilReady implements WaitStrategy.
func (w *waitForLog) WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error {
if w.compileErr != nil {
return fmt.Errorf("invalid regex pattern: %w", w.compileErr)
}
ctx, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
// Stream logs and search for pattern
options := container.LogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
Timestamps: false,
}
logs, err := cli.ContainerLogs(ctx, containerID, options)
if err != nil {
return fmt.Errorf("failed to get container logs: %w", err)
}
defer func() { _ = logs.Close() }()
// Use bufio.Scanner to read complete lines, avoiding chunk-boundary false negatives
// where a pattern could be split across two Read calls.
// ContainerLogs respects context cancellation, so Scan() will unblock when the timeout fires.
scanner := bufio.NewScanner(logs)
for scanner.Scan() {
if w.pattern.MatchString(scanner.Text()) {
return nil
}
}
if ctx.Err() != nil {
return fmt.Errorf("timeout waiting for log pattern: %s", w.pattern.String())
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("error reading logs: %w", err)
}
return fmt.Errorf("container stopped before log pattern found: %s", w.pattern.String())
}
// waitForPort waits for a port to be listening.
type waitForPort struct {
port string
timeout time.Duration
}
// WaitForPort creates a wait strategy that waits for a port to be listening.
// Port format: "8080/tcp" or just "8080" (defaults to tcp).
func WaitForPort(port string) *waitForPort {
// Ensure port has protocol
if !strings.Contains(port, "/") {
port = port + "/tcp"
}
return &waitForPort{
port: port,
timeout: 60 * time.Second,
}
}
// WithStartupTimeout sets the timeout for the wait strategy.
func (w *waitForPort) WithStartupTimeout(timeout time.Duration) *waitForPort {
w.timeout = timeout
return w
}
// WaitUntilReady implements WaitStrategy.
func (w *waitForPort) WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error {
ctx, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for port %s", w.port)
case <-ticker.C:
// Get container details
inspect, err := cli.ContainerInspect(ctx, containerID)
if err != nil {
return fmt.Errorf("failed to inspect container: %w", err)
}
// Check if container is still running
if !inspect.State.Running {
return fmt.Errorf("container stopped while waiting for port %s", w.port)
}
// Get mapped port
portBindings := inspect.NetworkSettings.Ports
for containerPort, bindings := range portBindings {
if string(containerPort) == w.port && len(bindings) > 0 {
// Try to connect to the port
host := "localhost"
hostPort := bindings[0].HostPort
conn, err := (&net.Dialer{Timeout: 1 * time.Second}).DialContext(ctx, "tcp", fmt.Sprintf("%s:%s", host, hostPort))
if err == nil {
_ = conn.Close()
return nil // Port is ready
}
}
}
}
}
}
// waitForHTTP waits for an HTTP endpoint to return expected status.
type waitForHTTP struct {
port string
path string
expectedStatus int
timeout time.Duration
}
// WaitForHTTP creates a wait strategy that waits for an HTTP endpoint.
// Port format: "8080" or "8080/tcp"
// Path: HTTP path (e.g., "/health")
// Expected status: HTTP status code (e.g., 200)
func WaitForHTTP(port, path string, expectedStatus int) *waitForHTTP {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if !strings.Contains(port, "/") {
port = port + "/tcp"
}
return &waitForHTTP{
port: port,
path: path,
expectedStatus: expectedStatus,
timeout: 60 * time.Second,
}
}
// WithStartupTimeout sets the timeout for the wait strategy.
func (w *waitForHTTP) WithStartupTimeout(timeout time.Duration) *waitForHTTP {
w.timeout = timeout
return w
}
// WaitUntilReady implements WaitStrategy.
func (w *waitForHTTP) WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error {
ctx, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
httpClient := &http.Client{
Timeout: 2 * time.Second,
}
for {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for HTTP %s on port %s", w.path, w.port)
case <-ticker.C:
// Get container details
inspect, err := cli.ContainerInspect(ctx, containerID)
if err != nil {
return fmt.Errorf("failed to inspect container: %w", err)
}
// Check if container is still running
if !inspect.State.Running {
return fmt.Errorf("container stopped while waiting for HTTP endpoint")
}
// Get mapped port
portBindings := inspect.NetworkSettings.Ports
for containerPort, bindings := range portBindings {
if string(containerPort) == w.port && len(bindings) > 0 {
host := "localhost"
hostPort := bindings[0].HostPort
url := fmt.Sprintf("http://%s:%s%s", host, hostPort, w.path)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
continue
}
resp, err := httpClient.Do(req)
if err == nil {
_ = resp.Body.Close()
if resp.StatusCode == w.expectedStatus {
return nil // Endpoint is ready
}
}
}
}
}
}
}
// waitForHealthy waits for container health check to be healthy.
type waitForHealthy struct {
timeout time.Duration
}
// WaitForHealthy creates a wait strategy that waits for health check to pass.
// Container must have a HEALTHCHECK defined in Dockerfile or via Docker API.
func WaitForHealthy() *waitForHealthy {
return &waitForHealthy{
timeout: 60 * time.Second,
}
}
// WithStartupTimeout sets the timeout for the wait strategy.
func (w *waitForHealthy) WithStartupTimeout(timeout time.Duration) *waitForHealthy {
w.timeout = timeout
return w
}
// WaitUntilReady implements WaitStrategy.
func (w *waitForHealthy) WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error {
ctx, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return fmt.Errorf("timeout waiting for container to be healthy")
case <-ticker.C:
inspect, err := cli.ContainerInspect(ctx, containerID)
if err != nil {
return fmt.Errorf("failed to inspect container: %w", err)
}
// Check if container is still running
if !inspect.State.Running {
return fmt.Errorf("container stopped before becoming healthy")
}
// Check health status
if inspect.State.Health != nil && inspect.State.Health.Status == "healthy" {
return nil
}
}
}
}
// waitFunc wraps a custom wait function.
type waitFunc struct {
fn func(ctx context.Context, cli *client.Client, containerID string) error
timeout time.Duration
}
// WaitForFunc creates a wait strategy from a custom function.
// This allows users to implement their own wait logic.
func WaitForFunc(fn func(ctx context.Context, cli *client.Client, containerID string) error) *waitFunc {
return &waitFunc{
fn: fn,
timeout: 60 * time.Second,
}
}
// WithStartupTimeout sets the timeout for the wait strategy.
func (w *waitFunc) WithStartupTimeout(timeout time.Duration) *waitFunc {
w.timeout = timeout
return w
}
// WaitUntilReady implements WaitStrategy.
func (w *waitFunc) WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error {
ctx, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
return w.fn(ctx, cli, containerID)
}
// multiWait combines multiple wait strategies (ALL must pass).
// Note on timeout behavior: multiWait sets an outer deadline via WithStartupTimeout (default 120s).
// Each child strategy also has its own independent timeout. The effective timeout for each child
// is min(child timeout, remaining time on the outer deadline). To avoid unexpected early expiration,
// set the outer timeout to be at least as large as the sum of all child timeouts, or rely solely on
// the outer timeout by setting child timeouts to a large value.
type multiWait struct {
strategies []WaitStrategy
timeout time.Duration
}
// WaitForAll creates a wait strategy that waits for all strategies to pass.
func WaitForAll(strategies ...WaitStrategy) *multiWait {
return &multiWait{
strategies: strategies,
timeout: 120 * time.Second,
}
}
// WithStartupTimeout sets the timeout for the wait strategy.
func (w *multiWait) WithStartupTimeout(timeout time.Duration) *multiWait {
w.timeout = timeout
return w
}
// WaitUntilReady implements WaitStrategy.
func (w *multiWait) WaitUntilReady(ctx context.Context, cli *client.Client, containerID string) error {
ctx, cancel := context.WithTimeout(ctx, w.timeout)
defer cancel()
for i, strategy := range w.strategies {
if err := strategy.WaitUntilReady(ctx, cli, containerID); err != nil {
return fmt.Errorf("wait strategy %d failed: %w", i, err)
}
}
return nil
}
// ForListeningPort is an alias for WaitForPort for testcontainers compatibility.
func ForListeningPort(port string) *waitForPort {
return WaitForPort(port)
}