-
Notifications
You must be signed in to change notification settings - Fork 8
/
buildkit.go
328 lines (266 loc) · 10.4 KB
/
buildkit.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
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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cluster
import (
"context"
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"strings"
"syscall"
"time"
builderv1beta "buf.build/gen/go/namespace/cloud/protocolbuffers/go/proto/namespace/cloud/builder/v1beta"
controlapi "github.com/moby/buildkit/api/services/control"
types "github.com/moby/buildkit/api/types"
"github.com/moby/buildkit/client"
"github.com/spf13/cobra"
buildkitfw "namespacelabs.dev/foundation/framework/build/buildkit"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnapi"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/localexec"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
"namespacelabs.dev/foundation/internal/providers/nscloud/endpoint"
"namespacelabs.dev/foundation/internal/sdk/buildctl"
"namespacelabs.dev/foundation/internal/sdk/host"
"namespacelabs.dev/foundation/std/tasks"
)
func NewBuildkitCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "buildkit",
Short: "Buildkit-related functionality.",
Hidden: true,
}
cmd.AddCommand(newBuildctlCmd())
cmd.AddCommand(newBuildkitProxy())
return cmd
}
func newBuildctlCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "buildctl -- ...",
Short: "Run buildctl on the target build cluster.",
}
buildCluster := cmd.Flags().String("cluster", "", "Set the type of a the build cluster to use.")
platform := cmd.Flags().String("platform", "amd64", "One of amd64 or arm64.")
cmd.Flags().MarkDeprecated("cluster", "use --platform instead")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
if *buildCluster != "" && *platform != "" {
return fnerrors.New("--cluster and --platform are exclusive")
}
buildctlBin, err := buildctl.EnsureSDK(ctx, host.HostPlatform())
if err != nil {
return fnerrors.New("failed to download buildctl: %w", err)
}
plat, err := api.ParseBuildPlatform(*platform)
if err != nil {
return err
}
p, err := runBuildProxyWithRegistry(ctx, plat, false, false, false, nil)
if err != nil {
return err
}
defer p.Cleanup()
return runBuildctl(ctx, buildctlBin, p, args...)
})
return cmd
}
func newBuildkitProxy() *cobra.Command {
cmd := &cobra.Command{
Use: "proxy",
Short: "Run a platform-specific buildkit proxy.",
Args: cobra.NoArgs,
}
sockPath := cmd.Flags().String("sock_path", "", "If specified listens on the specified path.")
platform := cmd.Flags().String("platform", "amd64", "One of amd64, or arm64.")
background := cmd.Flags().String("background", "", "If specified runs the proxy in the background, and writes the process PID to the specified path.")
createAtStartup := cmd.Flags().Bool("create_at_startup", false, "If true, eagerly creates the build clusters.")
useGrpcProxy := cmd.Flags().Bool("use_grpc_proxy", true, "If set, traffic is proxied with transparent grpc proxy instead of raw network proxy.")
_ = cmd.Flags().MarkHidden("use_grpc_proxy")
staticWorkerDefFile := cmd.Flags().String("static_worker_definition_path", "", "Injects the gRPC proxy ListWorkers response JSON payload from file")
_ = cmd.Flags().MarkHidden("static_worker_definition_path")
controlSockPath := cmd.Flags().String("control_sock_path", "", "If set, status HTTP server listens to this unix socket path.")
_ = cmd.Flags().MarkHidden("control_sock_path")
annotateBuild := cmd.Flags().Bool("annotate_build", true, "If set, annotate builds when running in Namespace instances.")
_ = cmd.Flags().MarkHidden("annotate_build")
buildkitSockPath := cmd.Flags().String("buildkit_sock_path", "", "If set, the proxy connect to a local unix socket rather than remote builder.")
_ = cmd.Flags().MarkHidden("buildkit_sock_path")
cmd.RunE = fncobra.RunE(func(ctx context.Context, _ []string) error {
plat, err := api.ParseBuildPlatform(*platform)
if err != nil {
return err
}
if !*useGrpcProxy && *staticWorkerDefFile != "" {
return fnerrors.New("--inject_worker_info requires --use_grpc_proxy")
}
if *background != "" {
if *sockPath == "" {
return fnerrors.New("--background requires --sock_path")
}
pid, err := startBackgroundProxy(ctx, buildxInstanceMetadata{SocketPath: *sockPath, Platform: plat, ControlSocketPath: *controlSockPath}, *createAtStartup, *useGrpcProxy, *annotateBuild, *staticWorkerDefFile, *buildkitSockPath)
if err != nil {
return err
}
return os.WriteFile(*background, []byte(fmt.Sprintf("%d", pid)), 0644)
}
workerInfoResp, err := parseInjectWorkerInfo(*staticWorkerDefFile, plat)
if err != nil {
return fnerrors.New("failed to parse worker info JSON payload: %v", err)
}
bp, err := runBuildProxy(ctx, plat, *sockPath, *controlSockPath, *buildkitSockPath, *createAtStartup, *useGrpcProxy, *annotateBuild, workerInfoResp)
if err != nil {
return err
}
eg := executor.New(ctx, "proxy")
eg.Go(func(ctx context.Context) error {
<-ctx.Done()
return bp.Cleanup()
})
eg.Go(func(ctx context.Context) error {
return bp.Serve(ctx)
})
if *controlSockPath != "" {
eg.Go(func(ctx context.Context) error {
return bp.ServeStatus(ctx)
})
fmt.Fprintf(console.Stderr(ctx), "Status server listening on %s\n", bp.controlSocketPath)
}
fmt.Fprintf(console.Stderr(ctx), "Listening on %s\n", bp.socketPath)
if err := eg.Wait(); err != nil {
return err
}
return nil
})
return cmd
}
func parseInjectWorkerInfo(workerInfoFile string, requiredPlatform api.BuildPlatform) (*controlapi.ListWorkersResponse, error) {
var workerDefData []byte
if workerInfoFile != "" {
workerInfo, err := os.ReadFile(workerInfoFile)
if err != nil {
return nil, err
}
workerDefData = workerInfo
} else {
// Settlemint uses the buildx also for local dev, but tenant token expires after 24h.
// API returns an authz error, but buildx does not show the error unless we unstuck it from its
// known bug where it block on ListWorkers buildkit API call for ever.
// So, embed the shortcut list worker payload:
workerDefData = []byte(staticWorkerDef)
}
f := &controlapi.ListWorkersResponse{}
if err := json.Unmarshal(workerDefData, f); err != nil {
return nil, err
}
// Include only the worker definitions that include *at least* one
// platform matching the proxy's (e.g. [arm64,amd64] worker matches for arm64 proxy)
newRecords := []*types.WorkerRecord{}
for _, r := range f.Record {
platformLoop:
for _, plat := range r.Platforms {
if plat.Architecture == string(requiredPlatform) {
newRecords = append(newRecords, r)
break platformLoop
}
}
}
f.Record = newRecords
return f, nil
}
func startBackgroundProxy(ctx context.Context, md buildxInstanceMetadata, connect bool, useGrpcProxy, annotateBuild bool, staticWorkerDefFile, buildkitSockPath string) (int, error) {
if connect {
// Make sure the cluster exists before going to the background.
if _, err := ensureBuildCluster(ctx, md.Platform); err != nil {
return 0, err
}
}
cmd := exec.Command(os.Args[0], "buildkit", "proxy", "--sock_path="+md.SocketPath,
"--platform="+string(md.Platform), "--region="+endpoint.RegionName, "--control_sock_path="+md.ControlSocketPath)
if md.DebugLogPath != "" {
cmd.Args = append(cmd.Args, "--debug_to_file="+md.DebugLogPath)
}
if buildkitSockPath != "" {
cmd.Args = append(cmd.Args, "--buildkit_sock_path", buildkitSockPath)
}
if useGrpcProxy {
cmd.Args = append(cmd.Args, "--use_grpc_proxy")
if staticWorkerDefFile != "" {
cmd.Args = append(cmd.Args, "--static_worker_definition_path", staticWorkerDefFile)
}
if annotateBuild {
cmd.Args = append(cmd.Args, "--annotate_build")
}
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
}
fmt.Fprintf(console.Debug(ctx), "Running background command %q\n", strings.Join(cmd.Args, " "))
if err := cmd.Start(); err != nil {
return -1, err
}
pid := cmd.Process.Pid
// Make sure the child process is not cleaned up on exit.
if err := cmd.Process.Release(); err != nil {
return -1, err
}
return pid, nil
}
func runBuildctl(ctx context.Context, buildctlBin buildctl.Buildctl, p *buildProxyWithRegistry, args ...string) error {
cmdLine := []string{"--addr", "unix://" + p.BuildkitAddr}
cmdLine = append(cmdLine, args...)
fmt.Fprintf(console.Debug(ctx), "buildctl %s\n", strings.Join(cmdLine, " "))
buildctl := exec.CommandContext(ctx, string(buildctlBin), cmdLine...)
buildctl.Env = os.Environ()
buildctl.Env = append(buildctl.Env, fmt.Sprintf("DOCKER_CONFIG="+p.DockerConfigDir))
return localexec.RunInteractive(ctx, buildctl)
}
func ensureBuildCluster(ctx context.Context, platform api.BuildPlatform) (*builderv1beta.EnsureBuildInstanceResponse, error) {
response, err := api.EnsureBuildCluster(ctx, platform)
if err != nil {
return nil, err
}
if err := waitUntilReady(ctx, response); err != nil {
return nil, err
}
return response, nil
}
func resolveBuildkitService(response *builderv1beta.EnsureBuildInstanceResponse) (string, error) {
if override := os.Getenv("NSC_BUILDKIT_ENDPOINT_ADDRESS_OVERRIDE"); override != "" {
return override, nil
}
if response.Encapsulation != builderv1beta.Encapsulation_WEBSOCKET_TCPPROXY {
return "", fnerrors.New("unsupported encapsulation: %v", response.Encapsulation)
}
if response.Authentication != builderv1beta.Authentication_BEARER_TOKEN {
return "", fnerrors.New("unsupported authentication: %v", response.Authentication)
}
return response.Endpoint, nil
}
func waitUntilReady(ctx context.Context, response *builderv1beta.EnsureBuildInstanceResponse) error {
buildkitEndpoint, err := resolveBuildkitService(response)
if err != nil {
return err
}
return tasks.Action("buildkit.wait-until-ready").Run(ctx, func(ctx context.Context) error {
// We must fetch a token with our parent context, so we get a task sink etc.
token, err := fnapi.FetchToken(ctx)
if err != nil {
return err
}
return buildkitfw.WaitReadiness(ctx, 1*time.Minute, func(innerCtx context.Context) (*client.Client, error) {
return client.New(innerCtx, response.InstanceId, client.WithContextDialer(func(innerCtx context.Context, _ string) (net.Conn, error) {
return api.DialEndpointWithToken(innerCtx, token, buildkitEndpoint)
}))
})
})
}
func buildClusterOrDefault(bp string) string {
if bp == "" {
return buildCluster
}
return bp
}