Debian Codegraph @

buildkit/client/connhelper/dockercontainer/dockercontainer.go

raw
1 // Package dockercontainer provides connhelper for docker-container://<container>
2 package dockercontainer
3
4 import (
5 "context"
6 "net"
7 "net/url"
8
9 "github.com/docker/cli/cli/connhelper/commandconn"
10 "github.com/moby/buildkit/client/connhelper"
11 "github.com/pkg/errors"
12 )
13
14 func init() {
15 connhelper.Register("docker-container", Helper)
16 }
17
18 // Helper returns helper for connecting to a Docker container.
19 // Requires BuildKit v0.5.0 or later in the container.
20 func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) {
21 sp, err := SpecFromURL(u)
22 if err != nil {
23 return nil, err
24 }
25 return &connhelper.ConnectionHelper{
26 ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) {
27 ctxFlags := []string{}
28 if sp.Context != "" {
29 ctxFlags = append(ctxFlags, "--context="+sp.Context)
30 }
31 // using background context because context remains active for the duration of the process, after dial has completed
32 return commandconn.New(context.Background(), "docker", append(ctxFlags, []string{"exec", "-i", sp.Container, "buildctl", "dial-stdio"}...)...)
33 },
34 }, nil
35 }
36
37 // Spec
38 type Spec struct {
39 Context string
40 Container string
41 }
42
43 // SpecFromURL creates Spec from URL.
44 // URL is like docker-container://<container>?context=<context>
45 // Only <container> part is mandatory.
46 func SpecFromURL(u *url.URL) (*Spec, error) {
47 q := u.Query()
48 sp := Spec{
49 Context: q.Get("context"),
50 Container: u.Hostname(),
51 }
52 if sp.Container == "" {
53 return nil, errors.New("url lacks container name")
54 }
55 return &sp, nil
56 }