-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecutor.go
More file actions
564 lines (487 loc) · 14.4 KB
/
executor.go
File metadata and controls
564 lines (487 loc) · 14.4 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
package docker
import (
"context"
"fmt"
"io"
"strings"
"sync"
cerrdefs "github.com/containerd/errdefs"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"go.opentelemetry.io/otel/trace"
)
// Executor manages a Docker container lifecycle.
type Executor struct {
config *config
client *client.Client
containerID string
mu sync.RWMutex
otel *otelInstrumentation
}
// New creates a new Docker executor with functional options.
//
// Example with functional options:
//
// exec := docker.New(
// docker.WithImage("nginx:latest"),
// docker.WithPorts("80:8080"),
// docker.WithEnv("KEY=value"),
// )
//
// Example with ContainerRequest struct:
//
// req := docker.ContainerRequest{
// Image: "nginx:latest",
// ExposedPorts: []string{"80/tcp"},
// Env: map[string]string{"KEY": "value"},
// }
// exec := docker.New(docker.WithRequest(req))
//
// Example combining both:
//
// req := docker.ContainerRequest{Image: "nginx:latest"}
// exec := docker.New(
// docker.WithRequest(req),
// docker.WithOTelConfig(otelCfg), // Add observability
// )
func New(opts ...Option) (*Executor, error) {
cfg, err := newConfig(opts...)
if err != nil {
return nil, fmt.Errorf("failed to create config: %w", err)
}
// Create Docker client
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return nil, fmt.Errorf("failed to create Docker client: %w", err)
}
exec := &Executor{
config: cfg,
client: cli,
}
// Initialize OTel if configured
if cfg.otelConfig != nil {
exec.otel = newOTelInstrumentation(cfg.otelConfig)
}
return exec, nil
}
// NewFromRequest creates a new Docker executor from a ContainerRequest struct.
// Additional options can be passed to override or extend the request configuration.
//
// Example with just struct:
//
// req := docker.ContainerRequest{
// Image: "nginx:latest",
// Env: map[string]string{"KEY": "value"},
// }
// exec, err := docker.NewFromRequest(req)
//
// Example with additional options (options override struct fields):
//
// req := docker.ContainerRequest{
// Image: "nginx:latest",
// Name: "default-name",
// }
// exec, err := docker.NewFromRequest(req,
// docker.WithName("override-name"), // Overrides struct name
// docker.WithOTelConfig(otelCfg), // Adds observability
// docker.WithPorts("80:8080"), // Adds port mapping
// )
func NewFromRequest(req ContainerRequest, opts ...Option) (*Executor, error) {
// Prepend WithRequest so additional options can override struct fields
allOpts := append([]Option{WithRequest(req)}, opts...)
return New(allOpts...)
}
// Start pulls the image (if needed), creates and starts the container.
// If a wait strategy is configured, it blocks until the container is ready.
func (e *Executor) Start(ctx context.Context) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.client == nil {
return fmt.Errorf("executor has been closed")
}
// Guard against double-start which would leak containers.
if e.containerID != "" {
return fmt.Errorf("container already started: %s", e.containerID)
}
// Trace with OTel
if e.otel != nil {
var span trace.Span
ctx, span = e.otel.startSpan(ctx, "docker.Start")
defer span.End()
}
// Pull image
if err := e.pullImage(ctx); err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "pull_image_error", err)
}
return fmt.Errorf("failed to pull image: %w", err)
}
// Create container
containerID, err := e.createContainer(ctx)
if err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "create_container_error", err)
}
return fmt.Errorf("failed to create container: %w", err)
}
e.containerID = containerID
// Start container
if err := e.client.ContainerStart(ctx, containerID, container.StartOptions{}); err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "start_container_error", err)
}
return fmt.Errorf("failed to start container: %w", err)
}
// Wait for readiness if strategy is configured
if e.config.waitStrategy != nil {
if err := e.config.waitStrategy.WaitUntilReady(ctx, e.client, containerID); err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "wait_strategy_error", err)
}
// Container failed to become ready, clean up
_ = e.terminate(ctx) //nolint:errcheck // Best effort cleanup, original error is more important
return fmt.Errorf("container failed to become ready: %w", err)
}
}
if e.otel != nil {
e.otel.incrementCounter(ctx, "containers_started", 1)
}
return nil
}
// Stop gracefully stops the container (sends SIGTERM).
// The container can still be restarted after stopping.
// Note: There is a small TOCTOU window between the containerID check and the Docker API call.
// Concurrent Terminate() may cause a benign "container not found" error.
func (e *Executor) Stop(ctx context.Context) error {
e.mu.RLock()
containerID := e.containerID
e.mu.RUnlock()
if containerID == "" {
return fmt.Errorf("container not started")
}
// Trace with OTel
if e.otel != nil {
var span trace.Span
ctx, span = e.otel.startSpan(ctx, "docker.Stop")
defer span.End()
}
timeout := int(e.config.timeout.Seconds())
stopOptions := container.StopOptions{
Timeout: &timeout,
}
if err := e.client.ContainerStop(ctx, containerID, stopOptions); err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "stop_container_error", err)
}
return fmt.Errorf("failed to stop container: %w", err)
}
if e.otel != nil {
e.otel.incrementCounter(ctx, "containers_stopped", 1)
}
return nil
}
// Terminate forcefully stops and removes the container.
// This is a destructive operation and the container cannot be restarted.
func (e *Executor) Terminate(ctx context.Context) error {
e.mu.Lock()
defer e.mu.Unlock()
return e.terminate(ctx)
}
// terminate is the internal implementation of Terminate (without locking).
func (e *Executor) terminate(ctx context.Context) error {
if e.containerID == "" {
return fmt.Errorf("container not started")
}
// Trace with OTel
if e.otel != nil {
var span trace.Span
ctx, span = e.otel.startSpan(ctx, "docker.Terminate")
defer span.End()
}
// Remove container (force stop if running)
removeOptions := container.RemoveOptions{
Force: true,
RemoveVolumes: true,
}
if err := e.client.ContainerRemove(ctx, e.containerID, removeOptions); err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "terminate_container_error", err)
}
return fmt.Errorf("failed to remove container: %w", err)
}
if e.otel != nil {
e.otel.incrementCounter(ctx, "containers_terminated", 1)
}
e.containerID = ""
return nil
}
// Restart restarts the container.
// Note: There is a small TOCTOU window between the containerID check and the Docker API call.
// Concurrent Terminate() may cause a benign "container not found" error.
func (e *Executor) Restart(ctx context.Context) error {
e.mu.RLock()
containerID := e.containerID
e.mu.RUnlock()
if containerID == "" {
return fmt.Errorf("container not started")
}
// Trace with OTel
if e.otel != nil {
var span trace.Span
ctx, span = e.otel.startSpan(ctx, "docker.Restart")
defer span.End()
}
timeout := int(e.config.timeout.Seconds())
restartOptions := container.StopOptions{
Timeout: &timeout,
}
if err := e.client.ContainerRestart(ctx, containerID, restartOptions); err != nil {
if e.otel != nil {
e.otel.recordError(ctx, "restart_container_error", err)
}
return fmt.Errorf("failed to restart container: %w", err)
}
if e.otel != nil {
e.otel.incrementCounter(ctx, "containers_restarted", 1)
}
return nil
}
// Wait blocks until the container stops and returns its exit code.
func (e *Executor) Wait(ctx context.Context) (int64, error) {
e.mu.RLock()
containerID := e.containerID
e.mu.RUnlock()
if containerID == "" {
return 0, fmt.Errorf("container not started")
}
// Trace with OTel
if e.otel != nil {
var span trace.Span
ctx, span = e.otel.startSpan(ctx, "docker.Wait")
defer span.End()
}
statusCh, errCh := e.client.ContainerWait(ctx, containerID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if e.otel != nil {
e.otel.recordError(ctx, "wait_container_error", err)
}
return 0, fmt.Errorf("error waiting for container: %w", err)
case status := <-statusCh:
return status.StatusCode, nil
}
}
// ContainerID returns the Docker container ID.
// Returns empty string if container hasn't been started yet.
func (e *Executor) ContainerID() string {
e.mu.RLock()
defer e.mu.RUnlock()
return e.containerID
}
// Close closes the Docker client connection.
// The container is NOT terminated automatically - call Terminate() first if needed.
// After Close(), any method that uses the Docker client will return an error.
func (e *Executor) Close() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.client == nil {
return nil
}
err := e.client.Close()
e.client = nil
return err
}
// pullImage pulls the container image if not already present.
func (e *Executor) pullImage(ctx context.Context) error {
// Check if image exists locally
_, err := e.client.ImageInspect(ctx, e.config.image)
if err == nil {
return nil // image exists
}
if !cerrdefs.IsNotFound(err) {
return fmt.Errorf("failed to inspect image %s: %w", e.config.image, err)
}
// Image not found, proceed to pull
// Pull image
reader, err := e.client.ImagePull(ctx, e.config.image, image.PullOptions{})
if err != nil {
return err
}
defer func() { _ = reader.Close() }()
// Consume output to ensure pull completes
_, err = io.Copy(io.Discard, reader)
return err
}
// createContainer creates the container with configured options.
func (e *Executor) createContainer(ctx context.Context) (string, error) {
// Build environment variables slice
env := make([]string, 0, len(e.config.env))
for k, v := range e.config.env {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
// Container configuration
containerConfig := &container.Config{
Image: e.config.image,
Cmd: e.config.cmd,
Entrypoint: e.config.entrypoint,
Env: env,
ExposedPorts: e.config.exposedPorts,
Labels: e.config.labels,
WorkingDir: e.config.workDir,
User: e.config.user,
Hostname: e.config.hostname,
Volumes: e.config.volumes,
}
// Host configuration
hostConfig := &container.HostConfig{
PortBindings: e.config.portBindings,
Binds: e.config.binds,
AutoRemove: e.config.autoRemove,
Privileged: e.config.privileged,
CapAdd: e.config.capAdd,
CapDrop: e.config.capDrop,
Tmpfs: e.config.tmpfs,
ShmSize: e.config.shmSize,
}
// Set network mode if specified
if e.config.networkMode != "" {
hostConfig.NetworkMode = container.NetworkMode(e.config.networkMode)
}
// Network configuration
networkConfig := &network.NetworkingConfig{}
if len(e.config.networks) > 0 {
endpoints := make(map[string]*network.EndpointSettings)
for _, net := range e.config.networks {
endpoints[net] = &network.EndpointSettings{}
}
networkConfig.EndpointsConfig = endpoints
}
// Create container
resp, err := e.client.ContainerCreate(
ctx,
containerConfig,
hostConfig,
networkConfig,
nil,
e.config.name,
)
if err != nil {
return "", err
}
return resp.ID, nil
}
// Logs returns all container logs as a string.
// Use LogOptions for more control.
func (e *Executor) Logs(ctx context.Context, opts ...LogOption) (string, error) {
e.mu.RLock()
containerID := e.containerID
e.mu.RUnlock()
if containerID == "" {
return "", fmt.Errorf("container not started")
}
logOpts := defaultLogOptions()
for _, opt := range opts {
opt(logOpts)
}
options := container.LogsOptions{
ShowStdout: logOpts.stdout,
ShowStderr: logOpts.stderr,
Timestamps: logOpts.timestamps,
Follow: false,
Tail: logOpts.tail,
Since: logOpts.since,
Until: logOpts.until,
}
logs, err := e.client.ContainerLogs(ctx, containerID, options)
if err != nil {
return "", fmt.Errorf("failed to get logs: %w", err)
}
defer func() { _ = logs.Close() }()
// Read all logs
var buf strings.Builder
_, err = stdcopy.StdCopy(&buf, &buf, logs)
if err != nil {
return "", fmt.Errorf("failed to read logs: %w", err)
}
return buf.String(), nil
}
// StreamLogs streams container logs to a channel.
// The channel is closed when streaming completes or context is canceled.
// Docker multiplexed stream headers are parsed to correctly identify stdout vs stderr.
func (e *Executor) StreamLogs(ctx context.Context, opts ...LogOption) (<-chan LogEntry, <-chan error) {
logCh := make(chan LogEntry, 100)
errCh := make(chan error, 1)
go func() {
defer close(logCh)
defer close(errCh)
e.mu.RLock()
containerID := e.containerID
e.mu.RUnlock()
if containerID == "" {
errCh <- fmt.Errorf("container not started")
return
}
logOpts := defaultLogOptions()
for _, opt := range opts {
opt(logOpts)
}
options := container.LogsOptions{
ShowStdout: logOpts.stdout,
ShowStderr: logOpts.stderr,
Timestamps: logOpts.timestamps,
Follow: logOpts.follow,
Tail: logOpts.tail,
Since: logOpts.since,
Until: logOpts.until,
}
logs, err := e.client.ContainerLogs(ctx, containerID, options)
if err != nil {
errCh <- fmt.Errorf("failed to get logs: %w", err)
return
}
defer func() { _ = logs.Close() }()
// Demux Docker multiplexed stream.
// Each frame has an 8-byte header: [stream_type, 0, 0, 0, size_be32...]
// stream_type: 1 = stdout, 2 = stderr
hdr := make([]byte, 8)
for {
_, err := io.ReadFull(logs, hdr)
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF && ctx.Err() == nil {
errCh <- fmt.Errorf("error reading log header: %w", err)
}
return
}
stream := "stdout"
if hdr[0] == 2 {
stream = "stderr"
}
// Frame payload size (big-endian uint32)
size := int(hdr[4])<<24 | int(hdr[5])<<16 | int(hdr[6])<<8 | int(hdr[7])
if size == 0 {
continue
}
payload := make([]byte, size)
_, err = io.ReadFull(logs, payload)
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF && ctx.Err() == nil {
errCh <- fmt.Errorf("error reading log payload: %w", err)
}
return
}
entry := LogEntry{
Stream: stream,
Content: string(payload),
}
select {
case logCh <- entry:
case <-ctx.Done():
return
}
}
}()
return logCh, errCh
}