-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdetect.go
More file actions
541 lines (470 loc) · 16.2 KB
/
Copy pathdetect.go
File metadata and controls
541 lines (470 loc) · 16.2 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
// Copyright 2026 The Gopherly Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package currus
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
)
// sentinel errors used internally by the detect layer; not exported because
// callers have no need to match on them specifically.
var (
errConfigDirUnknown = errors.New("docker config directory unknown")
errNoEndpointInContextMeta = errors.New("no docker endpoint in context metadata")
)
// New creates an Engine by detecting or constructing the appropriate backend.
//
// ctx applies to reachability checks ([Engine.Ping]) and daemon initialization
// during detection and construction.
//
// With no options, New probes endpoints in priority order until a reachable
// engine responds to [Engine.Ping]:
//
// 1. DOCKER_HOST env var (Docker engine; reads DOCKER_TLS_VERIFY and
// DOCKER_CERT_PATH for TLS)
// 2. CONTAINER_HOST env var (Podman engine)
// 3. DOCKER_CONTEXT env var (reads Docker context metadata)
// 4. Active context from ~/.docker/config.json
// (skipped when "default" or absent)
// 5. CONTAINER_ENGINE env var ("docker", "podman", or "containerd")
// 6. Docker socket (/var/run/docker.sock, then ~/.docker/run/docker.sock)
// 7. Podman rootless socket ($XDG_RUNTIME_DIR/podman/podman.sock or
// ~/.local/share/containers/podman/machine/podman.sock)
// 8. Podman rootful socket (/run/podman/podman.sock)
// 9. containerd socket (/run/containerd/containerd.sock)
//
// DOCKER_HOST and DOCKER_CONTEXT are mutually exclusive; setting both returns
// an error wrapping [ErrInvalidSpec].
//
// Use [WithEngine] to skip detection and select a backend explicitly.
// Use [WithEndpoint] to set the connection endpoint (see [Endpoint]).
//
// Errors:
// - [ErrNoEngine]: no candidate responds to [Engine.Ping]
// - [ErrInvalidSpec]: DOCKER_HOST and DOCKER_CONTEXT are both set, or TLS
// material is invalid
// - [ErrUnsupported]: [WithEngine] names an unknown kind
// - [ErrDaemonInfo]: the daemon responds but identity/capability query fails
// - Other errors wrap TLS, Docker context, or metadata failures
func New(ctx context.Context, opts ...Option) (Engine, error) {
cfg := buildEngineConfig(opts)
if cfg.kind != "" {
return openKind(ctx, cfg.kind, cfg)
}
if eng, err := envEndpoint(ctx, cfg); eng != nil || err != nil {
if err != nil {
return nil, err
}
return eng, nil
}
if envKind := engineKindFromEnv(); envKind != "" {
return openKind(ctx, envKind, cfg)
}
return autoDetect(ctx, cfg)
}
// MustNew is like [New] but panics on any error [New] would return.
// The panic message is prefixed with "currus.MustNew: ".
//
// Intended for package-level initialization or program startup where an
// unavailable engine is a programmer error, not a recoverable condition.
// Do not use MustNew in package code that might be called from tests or
// in contexts where the environment is not controlled.
func MustNew(ctx context.Context, opts ...Option) Engine {
eng, err := New(ctx, opts...)
if err != nil {
panic(fmt.Sprintf("currus.MustNew: %v", err))
}
return eng
}
// buildEngineConfig applies all options and returns the resulting engineConfig.
func buildEngineConfig(opts []Option) engineConfig {
var cfg engineConfig
for _, o := range opts {
if o != nil {
o(&cfg)
}
}
if cfg.logger == nil {
cfg.logger = slog.Default()
}
return cfg
}
// openKind constructs the engine for the given kind using the provided config.
// For Docker and Podman engines, it also calls resolveInfo to populate Caps.
func openKind(ctx context.Context, kind EngineKind, cfg engineConfig) (Engine, error) {
switch kind {
case Docker, Podman:
host := ""
if cfg.endpoint != nil {
host = cfg.endpoint.Host
}
tlsCfg, err := tlsConfigFromCurrus(endpointTLS(cfg.endpoint))
if err != nil {
return nil, fmt.Errorf("currus: %s TLS config: %w", kind, err)
}
dkind := dockerKindDocker
if kind == Podman {
dkind = dockerKindPodman
}
return buildAndResolveDockerEngine(ctx, dockerConfig{
Host: host,
DaemonSocket: resolveDaemonSocket(host, cfg.daemonSocket),
Kind: dkind,
TLS: tlsCfg,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
case Containerd:
socket := ""
ns := ""
if cfg.endpoint != nil {
socket = cfg.endpoint.Host
ns = cfg.endpoint.Namespace
}
// CONTAINERD_ADDRESS is the standard env var used by ctr and other containerd tools.
if socket == "" {
socket = os.Getenv("CONTAINERD_ADDRESS")
}
return newContainerdEngine(containerdConfig{
Socket: socket,
DaemonSocket: resolveDaemonSocket(socket, cfg.daemonSocket),
Namespace: ns,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
default:
return nil, fmt.Errorf("engine kind %q: %w", kind, ErrUnsupported)
}
}
// autoDetect probes the well-known socket paths in priority order.
func autoDetect(ctx context.Context, cfg engineConfig) (Engine, error) {
type candidate struct {
kind EngineKind
open func() (Engine, error)
socket string
}
dockerCandidate := func(socket string, dkind dockerDriverKind, kind EngineKind) candidate {
host := "unix://" + socket
return candidate{
kind: kind,
socket: socket,
open: func() (Engine, error) {
return newDockerEngine(dockerConfig{
Host: host,
DaemonSocket: resolveDaemonSocket(host, cfg.daemonSocket),
Kind: dkind,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
},
}
}
ctrdSocket := defaultContainerdSocket
candidates := []candidate{
dockerCandidate(defaultDockerSocket, dockerKindDocker, Docker),
dockerCandidate(dockerDesktopSocket(), dockerKindDocker, Docker),
dockerCandidate(podmanRootlessSocket(), dockerKindPodman, Podman),
dockerCandidate(defaultPodmanRootfulSocket, dockerKindPodman, Podman),
{
kind: Containerd,
socket: ctrdSocket,
open: func() (Engine, error) {
return newContainerdEngine(containerdConfig{
Socket: ctrdSocket,
DaemonSocket: resolveDaemonSocket(ctrdSocket, cfg.daemonSocket),
Logger: cfg.logger,
Tracer: cfg.tracer,
})
},
},
}
for _, c := range candidates {
if c.socket == "" {
continue
}
eng, err := c.open()
if err != nil {
cfg.logger.DebugContext(ctx, "engine candidate skipped (open failed)",
"kind", c.kind, "socket", c.socket, "err", err)
continue
}
if err = eng.Ping(ctx); err != nil {
cfg.logger.DebugContext(ctx, "engine candidate skipped (ping failed)",
"kind", c.kind, "socket", c.socket, "err", err)
_ = eng.Close() //nolint:errcheck // best-effort close on failed candidate
continue
}
if dEng, ok := eng.(*dockerEngine); ok {
if err = dEng.resolveInfo(ctx); err != nil {
cfg.logger.DebugContext(ctx, "engine candidate skipped (info failed)",
"kind", c.kind, "socket", c.socket, "err", err)
_ = eng.Close() //nolint:errcheck // best-effort close on failed candidate
continue
}
}
cfg.logger.DebugContext(ctx, "engine detected",
"kind", c.kind, "socket", c.socket)
return eng, nil
}
return nil, ErrNoEngine
}
// engineKindFromEnv reads the CONTAINER_ENGINE environment variable.
func engineKindFromEnv() EngineKind {
v := os.Getenv("CONTAINER_ENGINE")
switch EngineKind(v) {
case Docker, Podman, Containerd:
return EngineKind(v)
default:
return ""
}
}
// endpointTLS extracts the TLSConfig from an Endpoint, returning nil if the
// endpoint is nil or has no TLS configuration.
func endpointTLS(ep *Endpoint) *TLSConfig {
if ep == nil {
return nil
}
return ep.TLS
}
// podmanRootlessSocket returns the best-effort rootless Podman socket path
// for the current user, or "" if it cannot be determined.
func podmanRootlessSocket() string {
if xdg := os.Getenv("XDG_RUNTIME_DIR"); xdg != "" {
return xdg + "/podman/podman.sock"
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return home + "/.local/share/containers/podman/machine/podman.sock"
}
// dockerDesktopSocket returns the Docker Desktop socket path on macOS
// (~/.docker/run/docker.sock), or "" if the home directory cannot be determined.
func dockerDesktopSocket() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return home + "/.docker/run/docker.sock"
}
// buildAndResolveDockerEngine creates a dockerEngine from dcfg and immediately
// calls resolveInfo to populate Caps. On any error the engine is closed and
// the error is returned.
func buildAndResolveDockerEngine(ctx context.Context, dcfg dockerConfig) (*dockerEngine, error) {
eng, err := newDockerEngine(dcfg)
if err != nil {
return nil, err
}
if err = eng.resolveInfo(ctx); err != nil {
_ = eng.Close() //nolint:errcheck // best-effort close on failed init
return nil, err
}
return eng, nil
}
// envEndpoint resolves an Engine from Docker and Podman environment variables
// and the active Docker context. It returns (nil, nil) when no relevant
// variable is set, signaling New to continue to the next detection step.
//
// Resolution order:
// 1. DOCKER_HOST (Docker; reads DOCKER_TLS_VERIFY and DOCKER_CERT_PATH)
// 2. CONTAINER_HOST (Podman)
// 3. DOCKER_CONTEXT (Docker context by name)
// 4. Active context from ~/.docker/config.json
func envEndpoint(ctx context.Context, cfg engineConfig) (Engine, error) {
dockerHost := os.Getenv("DOCKER_HOST")
dockerContext := os.Getenv("DOCKER_CONTEXT")
if dockerHost != "" && dockerContext != "" {
return nil, fmt.Errorf("currus: %w: DOCKER_HOST and DOCKER_CONTEXT are mutually exclusive", ErrInvalidSpec)
}
if dockerHost != "" {
return envEndpointDockerHost(ctx, dockerHost, cfg)
}
if containerHost := os.Getenv("CONTAINER_HOST"); containerHost != "" {
return buildAndResolveDockerEngine(ctx, dockerConfig{
Host: containerHost,
DaemonSocket: resolveDaemonSocket(containerHost, cfg.daemonSocket),
Kind: dockerKindPodman,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
}
return envEndpointContext(ctx, dockerContext, cfg)
}
// envEndpointDockerHost resolves an engine from the DOCKER_HOST environment
// variable, reading TLS configuration from DOCKER_TLS_VERIFY / DOCKER_CERT_PATH.
func envEndpointDockerHost(ctx context.Context, dockerHost string, cfg engineConfig) (Engine, error) {
currusTLS, err := dockerTLSFromEnv()
if err != nil {
return nil, fmt.Errorf("currus: DOCKER_HOST TLS: %w", err)
}
tlsCfg, err := tlsConfigFromCurrus(currusTLS)
if err != nil {
return nil, fmt.Errorf("currus: DOCKER_HOST TLS: %w", err)
}
return buildAndResolveDockerEngine(ctx, dockerConfig{
Host: dockerHost,
DaemonSocket: resolveDaemonSocket(dockerHost, cfg.daemonSocket),
Kind: dockerKindDocker,
TLS: tlsCfg,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
}
// envEndpointContext resolves an engine from the active Docker context,
// consulting DOCKER_CONTEXT first and then ~/.docker/config.json.
func envEndpointContext(ctx context.Context, dockerContext string, cfg engineConfig) (Engine, error) {
configDir := dockerConfigDir()
if dockerContext != "" {
host, err := contextEndpoint(configDir, dockerContext)
if err != nil {
return nil, fmt.Errorf("currus: DOCKER_CONTEXT %q: %w", dockerContext, err)
}
return buildAndResolveDockerEngine(ctx, dockerConfig{
Host: host,
DaemonSocket: resolveDaemonSocket(host, cfg.daemonSocket),
Kind: dockerKindDocker,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
}
if name := activeContextName(configDir); name != "" {
host, err := contextEndpoint(configDir, name)
if err != nil {
return nil, fmt.Errorf("currus: active Docker context %q: %w", name, err)
}
return buildAndResolveDockerEngine(ctx, dockerConfig{
Host: host,
DaemonSocket: resolveDaemonSocket(host, cfg.daemonSocket),
Kind: dockerKindDocker,
Logger: cfg.logger,
Tracer: cfg.tracer,
})
}
return nil, nil //nolint:nilnil // intentional: no env config found, caller continues detection
}
// dockerTLSFromEnv builds a TLSConfig from DOCKER_TLS_VERIFY and
// DOCKER_CERT_PATH. Returns nil when DOCKER_TLS_VERIFY is not "1".
func dockerTLSFromEnv() (*TLSConfig, error) {
if os.Getenv("DOCKER_TLS_VERIFY") != "1" {
return nil, nil //nolint:nilnil // intentional: TLS not requested
}
certDir := os.Getenv("DOCKER_CERT_PATH")
if certDir == "" {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("determine home directory: %w", err)
}
certDir = filepath.Join(home, ".docker")
}
// G304: certDir comes from the DOCKER_CERT_PATH env var or the user's own
// ~/.docker directory — not from untrusted network or user input.
ca, err := os.ReadFile(filepath.Join(certDir, "ca.pem")) //nolint:gosec
if err != nil {
return nil, fmt.Errorf("read ca.pem: %w", err)
}
cert, err := os.ReadFile(filepath.Join(certDir, "cert.pem")) //nolint:gosec
if err != nil {
return nil, fmt.Errorf("read cert.pem: %w", err)
}
key, err := os.ReadFile(filepath.Join(certDir, "key.pem")) //nolint:gosec
if err != nil {
return nil, fmt.Errorf("read key.pem: %w", err)
}
return &TLSConfig{
CACert: ca,
Cert: cert,
Key: key,
}, nil
}
// dockerConfigDir returns the Docker configuration directory. It reads
// DOCKER_CONFIG if set and falls back to ~/.docker.
func dockerConfigDir() string {
if d := os.Getenv("DOCKER_CONFIG"); d != "" {
return d
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".docker")
}
// dockerConfigJSON is the subset of ~/.docker/config.json that currus reads.
// The JSON key "currentContext" is mandated by Docker's wire format, not our
// convention, so the tagliatelle snake_case rule is suppressed here.
//
//nolint:tagliatelle
type dockerConfigJSON struct {
CurrentContext string `json:"currentContext"`
}
// activeContextName reads the active Docker context name from config.json.
// It returns "" when the file is absent, unreadable, or the context is "default".
func activeContextName(configDir string) string {
if configDir == "" {
return ""
}
// G304: configDir is derived from DOCKER_CONFIG env var or ~/.docker — not
// from untrusted input.
data, err := os.ReadFile(filepath.Join(configDir, "config.json")) //nolint:gosec
if err != nil {
return ""
}
var cfg dockerConfigJSON
if err = json.Unmarshal(data, &cfg); err != nil {
return ""
}
if cfg.CurrentContext == "" || cfg.CurrentContext == "default" {
return ""
}
return cfg.CurrentContext
}
// dockerContextMeta is the subset of a Docker context meta.json that currus
// reads to find the Docker endpoint host.
// The JSON keys "Host" and "Endpoints" match Docker's meta.json wire format.
//
//nolint:tagliatelle
type dockerContextMeta struct {
Endpoints map[string]struct {
Host string `json:"Host"`
} `json:"Endpoints"`
}
// contextEndpoint returns the Docker daemon host URI for the named Docker
// context. It reads the context metadata from the standard Docker context
// store at configDir/contexts/meta/<sha256(name)>/meta.json.
func contextEndpoint(configDir, name string) (string, error) {
if configDir == "" {
return "", errConfigDirUnknown
}
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(name)))
metaPath := filepath.Join(configDir, "contexts", "meta", hash, "meta.json")
// G304: metaPath is constructed from configDir (DOCKER_CONFIG or ~/.docker)
// and the SHA-256 hash of the context name — not from untrusted input.
data, err := os.ReadFile(metaPath) //nolint:gosec
if err != nil {
return "", fmt.Errorf("read context metadata: %w", err)
}
var meta dockerContextMeta
if err = json.Unmarshal(data, &meta); err != nil {
return "", fmt.Errorf("parse context metadata: %w", err)
}
ep, ok := meta.Endpoints["docker"]
if !ok || ep.Host == "" {
return "", errNoEndpointInContextMeta
}
return ep.Host, nil
}