-
Notifications
You must be signed in to change notification settings - Fork 9
/
lowlevel.go
217 lines (175 loc) · 6.79 KB
/
lowlevel.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
// 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 tools
import (
"context"
"fmt"
"io/fs"
"net"
"os"
"reflect"
"time"
"github.com/moby/buildkit/client/llb"
"golang.org/x/exp/slices"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
"namespacelabs.dev/foundation/internal/artifacts/oci"
"namespacelabs.dev/foundation/internal/build"
"namespacelabs.dev/foundation/internal/build/buildkit"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/environment"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/grpcstdio"
"namespacelabs.dev/foundation/internal/llbutil"
"namespacelabs.dev/foundation/internal/planning/tool/protocol"
"namespacelabs.dev/foundation/internal/protos"
"namespacelabs.dev/foundation/internal/runtime/rtypes"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/std/tasks"
)
var LowLevelToolsProtocolVersion = 2
var InvocationCanUseBuildkit = false
const (
MaxInvocationDuration = 1 * time.Minute
)
type ResolveMethodFunc[Req, Resp proto.Message] func(*grpc.ClientConn) func(context.Context, Req, ...grpc.CallOption) (Resp, error)
type LowLevelInvokeOptions[Req, Resp proto.Message] struct {
RedactRequest func(proto.Message) proto.Message
RedactResponse func(proto.Message) proto.Message
}
func attachToAction(ctx context.Context, name string, msg proto.Message, redactMessage func(proto.Message) proto.Message) {
attachments := tasks.Attachments(ctx)
err := attachments.AttachSerializable(name+".textpb", "", redact(msg, redactMessage))
if err != nil {
fmt.Fprintf(console.Debug(ctx), "failed to serialize request: %v", err)
}
}
func (oo LowLevelInvokeOptions[Req, Resp]) Invoke(ctx context.Context, conf cfg.Configuration, pkg schema.PackageName, opts rtypes.RunToolOpts, req Req, resolve ResolveMethodFunc[Req, Resp]) (Resp, error) {
// XXX security: think through whether it is OK or not to expose Snapshots here.
// For now, assume not.
attachToAction(ctx, "request", req, oo.RedactRequest)
// The request and response are attached to the parent context.
var resp Resp
if err := tasks.Action("lowlevel.invocation").Arg("package", pkg).LogLevel(1).Run(ctx, func(ctx context.Context) error {
// os.Pipe is used instead of io.Pipe, as exec.Command will anyway behind the scenes
// create an additional io.Pipe to copy back to os.Pipe; as we need real pipes to communicate
// with the underlying process.
outr, outw, err := os.Pipe()
if err != nil {
return err
}
defer outr.Close()
defer outw.Close()
inr, inw, err := os.Pipe()
if err != nil {
return err
}
defer inr.Close()
defer inw.Close()
opts.Stdin = inr
opts.Stdout = outw
opts.Stderr = console.Output(ctx, pkg.String())
if !environment.IsRunningInCI() {
ctxWithTimeout, cancel := context.WithTimeout(ctx, MaxInvocationDuration)
defer cancel()
ctx = ctxWithTimeout
}
eg := executor.New(ctx, fmt.Sprintf("lowlevel.invoke(%s)", pkg))
eg.Go(func(ctx context.Context) error {
return RunWithOpts(ctx, conf, opts, func() {
version := LowLevelToolsProtocolVersion
if opts.SupportedToolVersion != 0 {
version = opts.SupportedToolVersion
}
// Only kick off the session after the binary is started; i.e. after the underlying
// image has been loaded. In CI in particular, access to docker has high contention and
// we see up to 20 secs waiting time loading an image.
eg.Go(func(ctx context.Context) error {
session, err := grpcstdio.NewSession(ctx, outr, inw, grpcstdio.WithVersion(version), grpcstdio.WithDefaults())
if err != nil {
return err
}
conn, err := grpc.DialContext(ctx, "stdio",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithReadBufferSize(0),
grpc.WithWriteBufferSize(0),
grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) {
return session.Dial(&grpcstdio.DialArgs{
StreamType: grpcstdio.DialArgs_STREAM_TYPE_GRPC,
ServiceName: protocol.InvocationService_ServiceDesc.ServiceName,
})
}))
if err != nil {
return err
}
defer conn.Close()
resp, err = resolve(conn)(ctx, req) // XXX lock?
return err
})
})
})
if err := eg.Wait(); err != nil {
return err
}
if reflect.ValueOf(resp).IsNil() {
return fnerrors.InternalError("never produced a response")
}
return nil
}); err != nil {
return resp, err
}
attachToAction(ctx, "response", resp, oo.RedactResponse)
return resp, nil
}
func (oo LowLevelInvokeOptions[Req, Resp]) InvokeOnBuildkit(ctx context.Context, conf cfg.Configuration, method string, pkg schema.PackageName, imageID oci.ImageID, opts rtypes.RunToolOpts, req Req) (Resp, error) {
return tasks.Return(ctx, tasks.Action("buildkit.invocation").Scope(pkg).Arg("ref", imageID.ImageRef()).Arg("method", method).LogLevel(1), func(ctx context.Context) (Resp, error) {
attachToAction(ctx, "request", req, oo.RedactRequest)
p := buildkit.HostPlatform()
base := llbutil.Image(imageID.RepoAndDigest(), p)
args := append(slices.Clone(opts.Command), opts.Args...)
args = append(args, "--inline_invocation="+method)
args = append(args, "--inline_invocation_input=/request/request.binarypb")
args = append(args, "--inline_invocation_output=/out/response.binarypb")
runOpts := []llb.RunOption{llb.ReadonlyRootFS(), llb.Network(llb.NetModeNone), llb.Args(args)}
if opts.WorkingDir != "" {
runOpts = append(runOpts, llb.Dir(opts.WorkingDir))
}
run := base.Run(runOpts...)
resp := protos.NewFromType[Resp]()
requestBytes, err := proto.Marshal(req)
if err != nil {
return resp, err
}
requestState := llb.Scratch().File(llb.Mkfile("request.binarypb", 0644, requestBytes))
run.AddMount("/request", requestState, llb.Readonly)
out := run.AddMount("/out", llb.Scratch())
output, err := buildkit.BuildFilesystem(ctx, conf, build.NewBuildTarget(&p).WithSourceLabel("Invocation %s", pkg).WithSourcePackage(pkg), out)
if err != nil {
return resp, err
}
fsys, err := compute.GetValue(ctx, output)
if err != nil {
return resp, err
}
responseBytes, err := fs.ReadFile(fsys, "response.binarypb")
if err != nil {
return resp, err
}
if err := proto.Unmarshal(responseBytes, resp); err != nil {
return resp, err
}
attachToAction(ctx, "response", resp, oo.RedactResponse)
return resp, nil
})
}
func redact(m proto.Message, f func(proto.Message) proto.Message) proto.Message {
if f == nil {
return m
}
return f(m)
}