-
Notifications
You must be signed in to change notification settings - Fork 9
/
buildproxy.go
259 lines (212 loc) · 6.78 KB
/
buildproxy.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
// 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"
"errors"
"fmt"
"log"
"net"
"os"
"path/filepath"
"sync"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/types"
"golang.org/x/sys/unix"
"namespacelabs.dev/foundation/framework/rpcerrors/multierr"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/files"
"namespacelabs.dev/foundation/internal/fnapi"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
"namespacelabs.dev/foundation/internal/workspace/dirs"
"namespacelabs.dev/foundation/std/tasks"
)
const (
nscrRegistryUsername = "token"
)
type BuildClusterInstance struct {
platform api.BuildPlatform
mu sync.Mutex
previous *api.CreateClusterResult
cancelRefresh func()
}
func (bp *BuildClusterInstance) NewConn(ctx context.Context) (net.Conn, error) {
// This is not our usual play; we're doing a lot of work with the lock held.
bp.mu.Lock()
defer bp.mu.Unlock()
if bp.previous != nil && (bp.previous.BuildCluster == nil || bp.previous.BuildCluster.Resumable) {
if _, err := api.EnsureCluster(ctx, api.Endpoint, bp.previous.ClusterId); err == nil {
return bp.rawDial(ctx, bp.previous)
}
}
response, err := api.CreateBuildCluster(ctx, api.Endpoint, bp.platform)
if err != nil {
return nil, err
}
if bp.cancelRefresh != nil {
bp.cancelRefresh()
bp.cancelRefresh = nil
}
if bp.previous == nil || bp.previous.ClusterId != response.ClusterId {
if err := waitUntilReady(ctx, response); err != nil {
fmt.Fprintf(console.Warnings(ctx), "Failed to wait for buildkit to become ready: %v\n", err)
}
}
if response.BuildCluster != nil && !response.BuildCluster.DoesNotRequireRefresh {
bp.cancelRefresh = api.StartBackgroundRefreshing(ctx, response.ClusterId)
}
bp.previous = response
return bp.rawDial(ctx, response)
}
func (bp *BuildClusterInstance) Cleanup() error {
bp.mu.Lock()
defer bp.mu.Unlock()
if bp.cancelRefresh != nil {
bp.cancelRefresh()
bp.cancelRefresh = nil
}
return nil
}
func (bp *BuildClusterInstance) rawDial(ctx context.Context, response *api.CreateClusterResult) (net.Conn, error) {
buildkitSvc, err := resolveBuildkitService(response)
if err != nil {
return nil, err
}
return api.DialEndpoint(ctx, buildkitSvc.Endpoint)
}
func NewBuildClusterInstance(ctx context.Context, platformStr string) (*BuildClusterInstance, error) {
clusterProfiles, err := api.GetProfile(ctx, api.Endpoint)
if err != nil {
return nil, err
}
platform := determineBuildClusterPlatform(clusterProfiles.ClusterPlatform, platformStr)
return NewBuildClusterInstance0(platform), nil
}
func NewBuildClusterInstance0(p api.BuildPlatform) *BuildClusterInstance {
return &BuildClusterInstance{platform: p}
}
type buildProxy struct {
socketPath string
sink tasks.ActionSink
instance *BuildClusterInstance
listener net.Listener
cleanup func() error
}
func runBuildProxy(ctx context.Context, requestedPlatform api.BuildPlatform, socketPath string, connectAtStart bool) (*buildProxy, error) {
bp, err := NewBuildClusterInstance(ctx, fmt.Sprintf("linux/%s", requestedPlatform))
if err != nil {
return nil, err
}
if connectAtStart {
if _, err := bp.NewConn(ctx); err != nil {
return nil, err
}
}
return bp.runBuildProxy(ctx, socketPath)
}
func (bp *BuildClusterInstance) runBuildProxy(ctx context.Context, socketPath string) (*buildProxy, error) {
var cleanup func() error
if socketPath == "" {
sockDir, err := dirs.CreateUserTempDir("", fmt.Sprintf("buildkit.%v", bp.platform))
if err != nil {
return nil, err
}
socketPath = filepath.Join(sockDir, "buildkit.sock")
cleanup = func() error {
return os.RemoveAll(sockDir)
}
} else {
if err := unix.Unlink(socketPath); err != nil && !os.IsNotExist(err) {
return nil, err
}
}
var d net.ListenConfig
listener, err := d.Listen(ctx, "unix", socketPath)
if err != nil {
_ = bp.Cleanup()
if cleanup != nil {
_ = cleanup()
}
return nil, err
}
sink := tasks.SinkFrom(ctx)
return &buildProxy{socketPath, sink, bp, listener, cleanup}, nil
}
func (bp *buildProxy) Cleanup() error {
var errs []error
errs = append(errs, bp.listener.Close())
errs = append(errs, bp.instance.Cleanup())
if bp.cleanup != nil {
errs = append(errs, bp.cleanup())
}
return multierr.New(errs...)
}
func (bp *buildProxy) Serve(ctx context.Context) error {
if err := serveProxy(ctx, bp.listener, func() (net.Conn, error) {
return bp.instance.NewConn(tasks.WithSink(context.Background(), bp.sink))
}); err != nil {
if x, ok := err.(*net.OpError); ok {
if x.Op == "accept" && errors.Is(x.Err, net.ErrClosed) {
return nil
}
}
return err
}
return nil
}
type buildProxyWithRegistry struct {
BuildkitAddr string
DockerConfigDir string
Cleanup func() error
}
func runBuildProxyWithRegistry(ctx context.Context, platform api.BuildPlatform, nscrOnlyRegistry bool) (*buildProxyWithRegistry, error) {
p, err := runBuildProxy(ctx, platform, "", true)
if err != nil {
return nil, err
}
go func() {
if err := p.Serve(ctx); err != nil {
log.Fatal(err)
}
}()
newConfig := *configfile.New(config.ConfigFileName)
if !nscrOnlyRegistry {
// This is a special option to support calling `nsc build --name`, which
// implies that they want to use nscr.io registry, without asking the user to
// set the credentials earlier with `nsc docker-login`.
// In that case we cannot copy the CredentialsStore from default config
// because MacOS Docker Engine would ignore the cleartext credentials we injected.
existing := config.LoadDefaultConfigFile(console.Stderr(ctx))
// We don't copy over all authentication settings; only some.
// XXX replace with custom buildctl invocation that merges auth in-memory.
newConfig.AuthConfigs = existing.AuthConfigs
newConfig.CredentialHelpers = existing.CredentialHelpers
newConfig.CredentialsStore = existing.CredentialsStore
}
nsRegs, err := api.GetImageRegistry(ctx, api.Endpoint)
if err != nil {
return nil, err
}
token, err := fnapi.FetchToken(ctx)
if err != nil {
return nil, err
}
for _, reg := range []*api.ImageRegistry{nsRegs.Registry, nsRegs.NSCR} {
if reg != nil {
newConfig.AuthConfigs[reg.EndpointAddress] = types.AuthConfig{
ServerAddress: reg.EndpointAddress,
Username: nscrRegistryUsername,
Password: token.Raw(),
}
}
}
tmpDir := filepath.Dir(p.socketPath)
credsFile := filepath.Join(tmpDir, config.ConfigFileName)
if err := files.WriteJson(credsFile, newConfig, 0600); err != nil {
p.Cleanup()
return nil, err
}
return &buildProxyWithRegistry{p.socketPath, tmpDir, p.Cleanup}, nil
}