forked from openllb/hlb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
66 lines (56 loc) · 1.94 KB
/
client.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
package hlb
import (
"context"
"net"
"github.com/docker/buildx/store/storeutil"
"github.com/docker/buildx/util/imagetools"
dockercommand "github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/flags"
"github.com/moby/buildkit/client"
"github.com/openllb/hlb/codegen"
"github.com/openllb/hlb/solver"
)
// Client returns a BuildKit client specified by addr based on BuildKit's
// connection helpers.
//
// If addr is empty, an attempt is made to connect to docker engine's embedded
// BuildKit which supports a subset of the exporters and special `moby`
// exporter.
func Client(ctx context.Context, addr string) (*client.Client, context.Context, error) {
// Attempt to connect to a healthy docker engine.
dockerCli, auth, err := NewDockerCli(ctx)
// If addr is empty, connect to BuildKit using connection helpers.
if addr != "" {
ctx = codegen.WithDockerAPI(ctx, dockerCli.Client(), auth, err, false)
cln, err := solver.BuildkitClient(ctx, addr)
return cln, ctx, err
}
// Otherwise, connect to docker engine's embedded BuildKit.
ctx = codegen.WithDockerAPI(ctx, dockerCli.Client(), auth, err, true)
cln, err := client.New(ctx, "", client.WithContextDialer(func(context.Context, string) (net.Conn, error) {
return dockerCli.Client().DialHijack(ctx, "/grpc", "h2c", nil)
}), client.WithSessionDialer(func(ctx context.Context, proto string, meta map[string][]string) (net.Conn, error) {
return dockerCli.Client().DialHijack(ctx, "/session", proto, meta)
}))
return cln, ctx, err
}
func NewDockerCli(ctx context.Context) (dockerCli *dockercommand.DockerCli, auth imagetools.Auth, err error) {
dockerCli, err = dockercommand.NewDockerCli()
if err != nil {
return
}
err = dockerCli.Initialize(flags.NewClientOptions())
if err != nil {
return
}
_, err = dockerCli.Client().ServerVersion(ctx)
if err != nil {
return
}
imageopt, err := storeutil.GetImageConfig(dockerCli, nil)
if err != nil {
return
}
auth = imageopt.Auth
return
}