forked from bazelbuild/remote-apis-sdks
/
server.go
462 lines (411 loc) · 14.9 KB
/
server.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package fakes
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/rexec"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
// Redundant imports are required for the google3 mirror. Aliases should not be changed.
rc "github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
bsgrpc "google.golang.org/genproto/googleapis/bytestream"
bspb "google.golang.org/genproto/googleapis/bytestream"
dpb "google.golang.org/protobuf/types/known/durationpb"
tspb "google.golang.org/protobuf/types/known/timestamppb"
)
// Server is a configurable fake in-process RBE server for use in integration tests.
type Server struct {
Exec *Exec
CAS *CAS
LogStreams *LogStreams
ActionCache *ActionCache
listener net.Listener
srv *grpc.Server
}
// NewServer creates a server that is ready to accept requests.
func NewServer(t testing.TB) (s *Server, err error) {
cas := NewCAS()
ls := NewLogStreams()
ac := NewActionCache()
s = &Server{Exec: NewExec(t, ac, cas), CAS: cas, LogStreams: ls, ActionCache: ac}
s.listener, err = net.Listen("tcp", ":0")
if err != nil {
return nil, err
}
s.srv = grpc.NewServer()
bsgrpc.RegisterByteStreamServer(s.srv, s)
regrpc.RegisterContentAddressableStorageServer(s.srv, s.CAS)
regrpc.RegisterActionCacheServer(s.srv, s.ActionCache)
regrpc.RegisterCapabilitiesServer(s.srv, s.Exec)
regrpc.RegisterExecutionServer(s.srv, s.Exec)
go s.srv.Serve(s.listener)
return s, nil
}
// Clear clears the fake results.
func (s *Server) Clear() {
s.CAS.Clear()
s.LogStreams.Clear()
s.ActionCache.Clear()
s.Exec.Clear()
}
// Stop shuts down the in process server.
func (s *Server) Stop() {
s.listener.Close()
s.srv.Stop()
}
// NewTestClient returns a new in-process Client connected to this server.
func (s *Server) NewTestClient(ctx context.Context) (*rc.Client, error) {
return rc.NewClient(ctx, "instance", s.dialParams())
}
// NewClientConn returns a gRPC client connction to the server.
func (s *Server) NewClientConn(ctx context.Context) (*grpc.ClientConn, error) {
p := s.dialParams()
conn, _, err := client.Dial(ctx, p.Service, p)
return conn, err
}
func (s *Server) dialParams() rc.DialParams {
return rc.DialParams{
Service: s.listener.Addr().String(),
NoSecurity: true,
}
}
// Read will serve both logstream and CAS resources, depending on the resource type indicated in the
// request.
func (s *Server) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
path := strings.Split(req.ResourceName, "/")
if len(path) < 2 || path[0] != "instance" {
return status.Errorf(codes.InvalidArgument, "test fake expected resource name of the form \"instance/<type>/...\", got %q", req.ResourceName)
}
if path[1] == "logstreams" {
return s.LogStreams.Read(req, stream)
} else if path[1] == "blobs" || path[1] == "compressed-blobs" {
return s.CAS.Read(req, stream)
}
return status.Errorf(codes.InvalidArgument, "invalid resource type: %q", path[1])
}
// Write writes a blob to CAS.
func (s *Server) Write(stream bsgrpc.ByteStream_WriteServer) error {
return s.CAS.Write(stream)
}
// QueryWriteStatus implements the corresponding RE API function.
func (*Server) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
return nil, status.Error(codes.Unimplemented, "test fake does not implement method")
}
// TestEnv is a wrapper for convenient integration tests of remote execution.
type TestEnv struct {
Client *rexec.Client
Server *Server
ExecRoot string
t testing.TB
}
// NewTestEnv initializes a TestEnv containing a fake server, a client connected to it,
// and a temporary directory used as execution root for inputs and outputs.
// It returns the new env and a cleanup function that should be called in the end of the test.
func NewTestEnv(t testing.TB) (*TestEnv, func()) {
t.Helper()
// Set up temp directory.
execRoot := t.TempDir()
// Set up the fake.
s, err := NewServer(t)
if err != nil {
t.Fatalf("Error starting fake server: %v", err)
}
grpcClient, err := s.NewTestClient(context.Background())
if err != nil {
t.Fatalf("Error connecting to server: %v", err)
}
return &TestEnv{
Client: &rexec.Client{
FileMetadataCache: filemetadata.NewNoopCache(),
GrpcClient: grpcClient,
},
Server: s,
ExecRoot: execRoot,
t: t,
}, func() {
grpcClient.Close()
s.Stop()
os.RemoveAll(execRoot)
}
}
func timeToProto(t time.Time) *tspb.Timestamp {
if t.IsZero() {
return nil
}
return tspb.New(t)
}
// Set sets up the fake to return the given result on the given command execution.
// It is not possible to make the fake result in a LocalErrorResultStatus or an InterruptedResultStatus.
func (e *TestEnv) Set(cmd *command.Command, opt *command.ExecutionOptions, res *command.Result, opts ...Option) (cmdDg, acDg, stderrDg, stdoutDg digest.Digest) {
e.t.Helper()
cmd.FillDefaultFieldValues()
if err := cmd.Validate(); err != nil {
e.t.Fatalf("command validation failed: %v", err)
}
t, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
ar := &repb.ActionResult{
ExitCode: int32(res.ExitCode),
ExecutionMetadata: &repb.ExecutedActionMetadata{
QueuedTimestamp: timeToProto(t.Add(time.Millisecond)),
WorkerStartTimestamp: timeToProto(t.Add(2 * time.Millisecond)),
WorkerCompletedTimestamp: timeToProto(t.Add(3 * time.Millisecond)),
InputFetchStartTimestamp: timeToProto(t.Add(4 * time.Millisecond)),
InputFetchCompletedTimestamp: timeToProto(t.Add(5 * time.Millisecond)),
ExecutionStartTimestamp: timeToProto(t.Add(6 * time.Millisecond)),
ExecutionCompletedTimestamp: timeToProto(t.Add(7 * time.Millisecond)),
OutputUploadStartTimestamp: timeToProto(t.Add(8 * time.Millisecond)),
OutputUploadCompletedTimestamp: timeToProto(t.Add(9 * time.Millisecond)),
},
}
for _, o := range opts {
if err := o.apply(ar, e.Server, e.ExecRoot); err != nil {
e.t.Fatalf("error applying option %+v: %v", o, err)
}
}
execRoot, workingDir, remoteWorkingDir := cmd.ExecRoot, cmd.WorkingDir, cmd.RemoteWorkingDir
root, inputs, _, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), execRoot, workingDir, remoteWorkingDir, cmd.InputSpec, e.Client.FileMetadataCache)
if err != nil {
e.t.Fatalf("error building input tree in fake setup: %v", err)
return digest.Empty, digest.Empty, digest.Empty, digest.Empty
}
for _, inp := range inputs {
ch, err := chunker.New(inp, false, int(e.Client.GrpcClient.ChunkMaxSize))
if err != nil {
e.t.Fatalf("error getting data from input entry: %v", err)
}
bytes, err := ch.FullData()
if err != nil {
e.t.Fatalf("error getting data from input chunker: %v", err)
}
e.Server.CAS.Put(bytes)
}
cmdPb := cmd.ToREProto(false)
bytes, err := proto.Marshal(cmdPb)
if err != nil {
e.t.Fatalf("error inserting command digest blob into CAS %v", err)
}
e.Server.CAS.Put(bytes)
cmdDg = digest.TestNewFromMessage(cmdPb)
ac := &repb.Action{
CommandDigest: cmdDg.ToProto(),
InputRootDigest: root.ToProto(),
DoNotCache: opt.DoNotCache,
}
if cmd.Timeout > 0 {
ac.Timeout = dpb.New(cmd.Timeout)
}
acDg = digest.TestNewFromMessage(ac)
if ar.StderrDigest != nil {
stderrDg = digest.NewFromProtoUnvalidated(ar.StderrDigest)
}
if ar.StdoutDigest != nil {
stdoutDg = digest.NewFromProtoUnvalidated(ar.StdoutDigest)
}
bytes, err = proto.Marshal(ac)
if err != nil {
e.t.Fatalf("error inserting action digest blob into CAS %v", err)
}
e.Server.CAS.Put(bytes)
e.Server.Exec.adg = acDg
e.Server.Exec.ActionResult = ar
switch res.Status {
case command.TimeoutResultStatus:
if res.Err == nil {
e.Server.Exec.Status = status.New(codes.DeadlineExceeded, "timeout")
} else {
e.Server.Exec.Status = status.New(codes.DeadlineExceeded, res.Err.Error())
}
case command.RemoteErrorResultStatus:
st, ok := status.FromError(res.Err)
if !ok {
if res.Err == nil {
st = status.New(codes.Internal, "remote error")
} else {
st = status.New(codes.Internal, res.Err.Error())
}
}
e.Server.Exec.Status = st
case command.CacheHitResultStatus:
if !e.Server.Exec.Cached { // Assume the user means in this case the actual ActionCache should miss.
e.Server.ActionCache.Put(acDg, ar)
}
}
return cmdDg, acDg, stderrDg, stdoutDg
}
// Option provides extra configuration for the test environment.
type Option interface {
apply(*repb.ActionResult, *Server, string) error
}
// InputFile to be made available to the fake action.
type InputFile struct {
Path string
Contents string
}
// Apply creates a file in the execroot with the given content
// and also inserts the file blob into CAS.
func (f *InputFile) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
bytes := []byte(f.Contents)
if err := os.MkdirAll(filepath.Join(execRoot, filepath.Dir(f.Path)), os.ModePerm); err != nil {
return fmt.Errorf("failed to create input dir %v: %v", filepath.Dir(f.Path), err)
}
err := os.WriteFile(filepath.Join(execRoot, f.Path), bytes, 0755)
if err != nil {
return fmt.Errorf("failed to setup file %v under temp exec root %v: %v", f.Path, execRoot, err)
}
s.CAS.Put(bytes)
return nil
}
// OutputFile is to be added as an output of the fake action.
type OutputFile struct {
Path string
Contents string
}
// Apply puts the file in the fake CAS and the given ActionResult.
func (f *OutputFile) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
bytes := []byte(f.Contents)
s.Exec.OutputBlobs = append(s.Exec.OutputBlobs, bytes)
dg := s.CAS.Put(bytes)
ac.OutputFiles = append(ac.OutputFiles, &repb.OutputFile{Path: f.Path, Digest: dg.ToProto()})
return nil
}
// OutputDir is to be added as an output of the fake action.
type OutputDir struct {
Path string
}
// Apply puts the file in the fake CAS and the given ActionResult.
func (d *OutputDir) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
root, ch, err := BuildDir(d.Path, s, execRoot)
if err != nil {
return fmt.Errorf("failed to build directory tree: %v", err)
}
tr := &repb.Tree{
Root: root,
Children: ch,
}
treeBlob, err := proto.Marshal(tr)
if err != nil {
return fmt.Errorf("failed to marshal tree: %v", err)
}
treeDigest := s.CAS.Put(treeBlob)
ac.OutputDirectories = append(ac.OutputDirectories, &repb.OutputDirectory{Path: d.Path, TreeDigest: treeDigest.ToProto()})
return nil
}
// OutputSymlink is to be added as an output of the fake action.
type OutputSymlink struct {
Path string
Target string
}
// Apply puts the file in the fake CAS and the given ActionResult.
func (l *OutputSymlink) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
ac.OutputFileSymlinks = append(ac.OutputFileSymlinks, &repb.OutputSymlink{Path: l.Path, Target: l.Target})
return nil
}
// BuildDir builds the directory tree by recursively iterating through the directory.
// This is similar to tree.go ComputeMerkleTree.
func BuildDir(path string, s *Server, execRoot string) (root *repb.Directory, childDir []*repb.Directory, err error) {
res := &repb.Directory{}
ch := []*repb.Directory{}
files, err := os.ReadDir(filepath.Join(execRoot, path))
if err != nil {
return nil, nil, fmt.Errorf("failed read directory: %v", err)
}
for _, file := range files {
fn := file.Name()
fp := filepath.Join(execRoot, path, fn)
if file.IsDir() {
root, _, err := BuildDir(fp, s, execRoot)
if err != nil {
return nil, nil, fmt.Errorf("failed to build directory tree: %v", err)
}
res.Directories = append(res.Directories, &repb.DirectoryNode{Name: fn, Digest: digest.TestNewFromMessage(root).ToProto()})
ch = append(ch, root)
} else {
content, err := os.ReadFile(fp)
if err != nil {
return nil, nil, fmt.Errorf("failed to read file: %v", err)
}
dg := s.CAS.Put(content)
res.Files = append(res.Files, &repb.FileNode{Name: fn, Digest: dg.ToProto()})
}
}
return res, ch, nil
}
// LogStream adds a new logstream that may be served from the bytestream API.
type LogStream struct {
// Name is the name of the stream. The stream may be downloaded by fetching the resource named
// instance/logstreams/<name> from bytestream.
Name string
// Chunks is a list of the chunks that will be sent by bytestream.
Chunks []string
}
func (l *LogStream) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
return s.LogStreams.Put(l.Name, l.Chunks...)
}
// StdOutStream causes the fake action to indicate this as the name of the stdout logstream.
type StdOutStream string
func (o StdOutStream) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
s.Exec.StdOutStreamName = string(o)
return nil
}
// StdErrStream causes the fake action to indicate this as the name of the stderr logstream.
type StdErrStream string
func (e StdErrStream) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
s.Exec.StdErrStreamName = string(e)
return nil
}
// StdOut is to be added as an output of the fake action.
type StdOut string
// Apply puts the action stdout in the fake CAS and the given ActionResult.
func (o StdOut) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
bytes := []byte(o)
s.Exec.OutputBlobs = append(s.Exec.OutputBlobs, bytes)
dg := s.CAS.Put(bytes)
ac.StdoutDigest = dg.ToProto()
return nil
}
// StdOutRaw is to be added as a raw output of the fake action.
type StdOutRaw string
// Apply puts the action stdout as raw bytes in the given ActionResult.
func (o StdOutRaw) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
ac.StdoutRaw = []byte(o)
return nil
}
// StdErr is to be added as an output of the fake action.
type StdErr string
// Apply puts the action stderr in the fake CAS and the given ActionResult.
func (o StdErr) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
bytes := []byte(o)
s.Exec.OutputBlobs = append(s.Exec.OutputBlobs, bytes)
dg := s.CAS.Put(bytes)
ac.StderrDigest = dg.ToProto()
return nil
}
// StdErrRaw is to be added as a raw output of the fake action.
type StdErrRaw string
// Apply puts the action stderr as raw bytes in the given ActionResult.
func (o StdErrRaw) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
ac.StderrRaw = []byte(o)
return nil
}
// ExecutionCacheHit of true will cause the ActionResult to be returned as a cache hit during
// fake execution.
type ExecutionCacheHit bool
// Apply on true will cause the ActionResult to be returned as a cache hit during fake execution.
func (c ExecutionCacheHit) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
s.Exec.Cached = bool(c)
return nil
}