This repository has been archived by the owner on Jun 21, 2023. It is now read-only.
/
test.go
412 lines (340 loc) · 7.85 KB
/
test.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
// Copyright (c) 2020 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
"os/signal"
"sync"
"syscall"
"gate.computer/gate/packet"
"gate.computer/grpc/api"
"github.com/google/uuid"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/wrapperspb"
"import.name/lock"
)
const (
serviceName = "test"
serviceRevision = "0"
)
func main() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGTERM)
network := flag.String("net", "", "listener network")
address := flag.String("addr", "", "listener address")
flag.Parse()
var err error
var l net.Listener
if *network != "" {
l, err = net.Listen(*network, *address)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
} else {
// File descriptor number chosen by executable.
conn, err := net.FileConn(os.NewFile(3, "fd 3"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
l = listenerFor(conn)
}
s := grpc.NewServer()
api.RegisterRootServer(s, new(rootServer))
api.RegisterInstanceServer(s, newInstanceServer())
go func() {
<-signals
s.Stop()
}()
if err := s.Serve(l); err != nil && err != io.EOF {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
type listener struct {
mu sync.Mutex
conn *listenConn
addr net.Addr
closed <-chan struct{}
}
func listenerFor(conn net.Conn) *listener {
closed := make(chan struct{})
return &listener{
conn: &listenConn{
Conn: conn,
closed: closed,
},
addr: conn.LocalAddr(),
closed: closed,
}
}
func (l *listener) Accept() (net.Conn, error) {
var c *listenConn
lock.Guard(&l.mu, func() {
c = l.conn
l.conn = nil
})
if c != nil {
return c, nil
}
<-l.closed
return nil, io.EOF
}
func (l *listener) Addr() net.Addr {
return l.addr
}
func (l *listener) Close() error {
var c *listenConn
lock.Guard(&l.mu, func() {
c = l.conn
l.conn = nil
})
if c == nil {
return nil
}
return c.Close()
}
type listenConn struct {
net.Conn
mu sync.Mutex
closed chan<- struct{}
}
func (c *listenConn) Close() error {
var ch chan<- struct{}
lock.Guard(&c.mu, func() {
ch = c.closed
c.closed = nil
})
if ch == nil {
return nil
}
defer close(ch)
return c.Conn.Close()
}
type rootServer struct {
api.UnimplementedRootServer
}
func (s *rootServer) Init(ctx context.Context, req *api.InitRequest) (*api.InitResponse, error) {
return &api.InitResponse{
Services: []*api.Service{
{
Name: serviceName,
Revision: serviceRevision,
},
},
}, nil
}
type instanceServer struct {
api.UnimplementedInstanceServer
mu sync.Mutex
instances map[string]*instance
}
func newInstanceServer() *instanceServer {
return &instanceServer{
instances: make(map[string]*instance),
}
}
func (s *instanceServer) registerInstance(inst *instance) (id []byte) {
id = newInstanceID()
lock.Guard(&s.mu, func() {
s.instances[string(id)] = inst
})
return
}
func (s *instanceServer) getInstance(id []byte) (*instance, error) {
return s.lookupInstance(id, false)
}
func (s *instanceServer) removeInstance(id []byte) (*instance, error) {
return s.lookupInstance(id, true)
}
func (s *instanceServer) lookupInstance(id []byte, remove bool) (inst *instance, err error) {
lock.Guard(&s.mu, func() {
inst = s.instances[string(id)]
if remove {
delete(s.instances, string(id))
}
})
if inst == nil {
err = errors.New("instance not found")
}
return
}
func (s *instanceServer) Create(ctx context.Context, req *api.CreateRequest) (*api.CreateResponse, error) {
inst := newInstance()
if err := inst.restore(req.Snapshot); err != nil {
return &api.CreateResponse{RestorationError: err.Error()}, nil
}
id := s.registerInstance(inst)
return &api.CreateResponse{Id: id}, nil
}
func (s *instanceServer) Receive(req *api.ReceiveRequest, stream api.Instance_ReceiveServer) error {
inst, err := s.getInstance(req.Id)
if err != nil {
return err
}
return inst.sendTo(stream)
}
func (s *instanceServer) Handle(ctx context.Context, req *api.HandleRequest) (*emptypb.Empty, error) {
inst, err := s.getInstance(req.Id)
if err != nil {
return nil, err
}
inst.handle(ctx, req.Data)
return new(emptypb.Empty), nil
}
func (s *instanceServer) Shutdown(ctx context.Context, req *api.ShutdownRequest) (*emptypb.Empty, error) {
inst, _ := s.removeInstance(req.Id)
if inst != nil {
inst.shutdown()
} else {
fmt.Fprintln(os.Stderr, "instance not found at shutdown")
}
return new(emptypb.Empty), nil
}
func (s *instanceServer) Suspend(ctx context.Context, req *api.SuspendRequest) (*emptypb.Empty, error) {
inst, err := s.getInstance(req.Id)
if err != nil {
return nil, err
}
inst.suspend()
return new(emptypb.Empty), nil
}
func (s *instanceServer) Snapshot(ctx context.Context, req *api.SnapshotRequest) (*wrapperspb.BytesValue, error) {
inst, err := s.removeInstance(req.Id)
if err != nil {
return nil, err
}
snapshot, err := inst.snapshot(ctx, req.Outgoing, req.Incoming)
if err != nil {
return nil, err
}
return &wrapperspb.BytesValue{Value: snapshot}, nil
}
func newInstanceID() []byte {
id := uuid.New()
return id[:]
}
type instance struct {
mu sync.Mutex
loopback chan packet.Buf
receiving <-chan struct{}
outgoing []byte
incoming []byte
}
func newInstance() *instance {
return &instance{
loopback: make(chan packet.Buf),
}
}
func (inst *instance) restore(snapshot []byte) error {
inst.mu.Lock()
defer inst.mu.Unlock()
for b := snapshot; len(b) > 0; {
if len(b) < packet.HeaderSize {
return errors.New("snapshot contains partial packet")
}
n := packet.Buf(b).EncodedSize()
if n < packet.HeaderSize || n > len(b) {
return errors.New("snapshot packet size out of bounds")
}
b = b[n:]
}
inst.outgoing = snapshot
return nil
}
func (inst *instance) sendTo(stream api.Instance_ReceiveServer) error {
done := make(chan struct{})
defer close(done)
var (
loopback <-chan packet.Buf
outgoing []byte
)
lock.Guard(&inst.mu, func() {
if inst.receiving == nil {
loopback = inst.loopback
if loopback != nil {
inst.receiving = done
outgoing = inst.outgoing
inst.outgoing = nil
}
}
})
if loopback == nil {
return errors.New("redundant reception")
}
for len(outgoing) > 0 {
n := packet.Buf(outgoing).EncodedSize()
if err := stream.Send(&wrapperspb.BytesValue{Value: outgoing[:n:n]}); err != nil {
lock.Guard(&inst.mu, func() {
inst.outgoing = outgoing
})
return err
}
outgoing = outgoing[n:]
}
for p := range loopback {
if err := stream.Send(&wrapperspb.BytesValue{Value: p}); err != nil {
lock.Guard(&inst.mu, func() {
inst.outgoing = p
})
return err
}
}
return nil
}
func (inst *instance) handle(ctx context.Context, p packet.Buf) {
var loopback chan<- packet.Buf
lock.Guard(&inst.mu, func() {
if len(inst.incoming) == 0 && inst.loopback != nil {
loopback = inst.loopback
}
})
if loopback != nil {
select {
case loopback <- p:
return
case <-ctx.Done():
}
}
lock.Guard(&inst.mu, func() {
inst.incoming = append(inst.incoming, p...)
})
}
func (inst *instance) shutdown() {
inst.mu.Lock()
defer inst.mu.Unlock()
if inst.loopback != nil {
close(inst.loopback)
inst.loopback = nil
}
}
func (inst *instance) suspend() {
inst.shutdown()
}
func (inst *instance) snapshot(ctx context.Context, outgoing, incoming []byte) ([]byte, error) {
inst.mu.Lock()
defer inst.mu.Unlock()
if inst.receiving != nil {
if inst.loopback != nil {
return nil, errors.New("snapshotting before suspension")
}
select {
case <-inst.receiving:
case <-ctx.Done():
return nil, ctx.Err()
}
}
snapshot := append(append(outgoing, inst.outgoing...), append(inst.incoming, incoming...)...)
inst.outgoing = nil
inst.incoming = nil
return snapshot, nil
}