/
relay_test.go
2134 lines (1846 loc) · 68.2 KB
/
relay_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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package tchannel_test
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"runtime"
"strings"
"sync"
"testing"
"time"
. "github.com/uber/tchannel-go"
"github.com/uber/tchannel-go/benchmark"
"github.com/uber/tchannel-go/raw"
"github.com/uber/tchannel-go/relay"
"github.com/uber/tchannel-go/relay/relaytest"
"github.com/uber/tchannel-go/testutils"
"github.com/uber/tchannel-go/testutils/testreader"
"github.com/uber/tchannel-go/testutils/thriftarg2test"
"github.com/uber/tchannel-go/thrift"
"github.com/uber/tchannel-go/thrift/arg2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
"golang.org/x/net/context"
)
type relayTest struct {
testutils.TestServer
}
func serviceNameOpts(s string) *testutils.ChannelOpts {
return testutils.NewOpts().SetServiceName(s)
}
func withRelayedEcho(t testing.TB, f func(relay, server, client *Channel, ts *testutils.TestServer)) {
opts := serviceNameOpts("test").
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
testutils.RegisterEcho(ts.Server(), nil)
client := ts.NewClient(serviceNameOpts("client"))
client.Peers().Add(ts.HostPort())
f(ts.Relay(), ts.Server(), client, ts)
})
}
func TestRelay(t *testing.T) {
withRelayedEcho(t, func(_, _, client *Channel, ts *testutils.TestServer) {
tests := []struct {
header string
body string
}{
{"fake-header", "fake-body"}, // fits in one frame
{"fake-header", strings.Repeat("fake-body", 10000)}, // requires continuation
}
sc := client.GetSubChannel("test")
for _, tt := range tests {
ctx, cancel := NewContext(time.Second)
defer cancel()
arg2, arg3, _, err := raw.CallSC(ctx, sc, "echo", []byte(tt.header), []byte(tt.body))
require.NoError(t, err, "Relayed call failed.")
assert.Equal(t, tt.header, string(arg2), "Header was mangled during relay.")
assert.Equal(t, tt.body, string(arg3), "Body was mangled during relay.")
}
calls := relaytest.NewMockStats()
for range tests {
calls.Add("client", "test", "echo").Succeeded().End()
}
ts.AssertRelayStats(calls)
})
}
func TestRelaySetHost(t *testing.T) {
rh := relaytest.NewStubRelayHost()
opts := serviceNameOpts("test").
SetRelayHost(rh).
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
testutils.RegisterEcho(ts.Server(), nil)
client := ts.NewClient(serviceNameOpts("client"))
client.Peers().Add(ts.HostPort())
testutils.AssertEcho(t, client, ts.HostPort(), ts.Server().ServiceName())
})
}
func TestRelayHandlesClosedPeers(t *testing.T) {
opts := serviceNameOpts("test").
SetRelayOnly().
SetCheckFramePooling().
// Disable logs as we are closing connections that can error in a lot of places.
DisableLogVerification()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
ctx, cancel := NewContext(300 * time.Millisecond)
defer cancel()
testutils.RegisterEcho(ts.Server(), nil)
client := ts.NewClient(serviceNameOpts("client"))
client.Peers().Add(ts.HostPort())
sc := client.GetSubChannel("test")
_, _, _, err := raw.CallSC(ctx, sc, "echo", []byte("fake-header"), []byte("fake-body"))
require.NoError(t, err, "Relayed call failed.")
ts.Server().Close()
require.NotPanics(t, func() {
raw.CallSC(ctx, sc, "echo", []byte("fake-header"), []byte("fake-body"))
})
})
}
func TestRelayConnectionCloseDrainsRelayItems(t *testing.T) {
opts := serviceNameOpts("s1").
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
ctx, cancel := NewContext(time.Second)
defer cancel()
s1 := ts.Server()
s2 := ts.NewServer(serviceNameOpts("s2"))
s2HP := s2.PeerInfo().HostPort
testutils.RegisterEcho(s1, func() {
// When s1 gets called, it calls Close on the connection from the relay to s2.
conn, err := ts.Relay().Peers().GetOrAdd(s2HP).GetConnection(ctx)
require.NoError(t, err, "Unexpected failure getting connection between s1 and relay")
conn.Close()
})
testutils.AssertEcho(t, s2, ts.HostPort(), "s1")
calls := relaytest.NewMockStats()
calls.Add("s2", "s1", "echo").Succeeded().End()
ts.AssertRelayStats(calls)
})
}
func TestRelayIDClash(t *testing.T) {
// TODO: enable framepool checks
opts := serviceNameOpts("s1").
SetRelayOnly()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
s1 := ts.Server()
s2 := ts.NewServer(serviceNameOpts("s2"))
unblock := make(chan struct{})
testutils.RegisterEcho(s1, func() {
<-unblock
})
testutils.RegisterEcho(s2, nil)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
testutils.AssertEcho(t, s2, ts.HostPort(), s1.ServiceName())
}()
}
for i := 0; i < 5; i++ {
testutils.AssertEcho(t, s1, ts.HostPort(), s2.ServiceName())
}
close(unblock)
wg.Wait()
})
}
func TestRelayErrorsOnGetPeer(t *testing.T) {
busyErr := NewSystemError(ErrCodeBusy, "busy")
tests := []struct {
desc string
returnPeer string
returnErr error
statsKey string
wantErr error
}{
{
desc: "No peer and no error",
returnPeer: "",
returnErr: nil,
statsKey: "relay-bad-relay-host",
wantErr: NewSystemError(ErrCodeDeclined, `bad relay host implementation`),
},
{
desc: "System error getting peer",
returnErr: busyErr,
statsKey: "relay-busy",
wantErr: busyErr,
},
{
desc: "Unknown error getting peer",
returnErr: errors.New("unknown"),
statsKey: "relay-declined",
wantErr: NewSystemError(ErrCodeDeclined, "unknown"),
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
f := func(relay.CallFrame, *relay.Conn) (string, error) {
return tt.returnPeer, tt.returnErr
}
opts := testutils.NewOpts().
SetRelayHost(relaytest.HostFunc(f)).
SetRelayOnly().
SetCheckFramePooling().
DisableLogVerification() // some of the test cases cause warnings.
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
client := ts.NewClient(nil)
err := testutils.CallEcho(client, ts.HostPort(), "svc", nil)
require.Error(t, err, "Call to unknown service should fail")
assert.Equal(t, tt.wantErr, err, "unexpected error")
calls := relaytest.NewMockStats()
calls.Add(client.PeerInfo().ServiceName, "svc", "echo").
Failed(tt.statsKey).End()
ts.AssertRelayStats(calls)
})
})
}
}
func TestErrorFrameEndsRelay(t *testing.T) {
// TestServer validates that there are no relay items left after the given func.
opts := serviceNameOpts("svc").
SetRelayOnly().
SetCheckFramePooling().
DisableLogVerification()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
client := ts.NewClient(nil)
err := testutils.CallEcho(client, ts.HostPort(), "svc", nil)
if !assert.Error(t, err, "Expected error due to unknown method") {
return
}
se, ok := err.(SystemError)
if !assert.True(t, ok, "err should be a SystemError, got %T", err) {
return
}
assert.Equal(t, ErrCodeBadRequest, se.Code(), "Expected BadRequest error")
calls := relaytest.NewMockStats()
calls.Add(client.PeerInfo().ServiceName, "svc", "echo").Failed("bad-request").End()
ts.AssertRelayStats(calls)
})
}
// Trigger a race between receiving a new call and a connection closing
// by closing the relay while a lot of background calls are being made.
func TestRaceCloseWithNewCall(t *testing.T) {
opts := serviceNameOpts("s1").
SetRelayOnly().
SetCheckFramePooling().
DisableLogVerification()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
s1 := ts.Server()
s2 := ts.NewServer(serviceNameOpts("s2").DisableLogVerification())
testutils.RegisterEcho(s1, nil)
// signal to start closing the relay.
var (
closeRelay sync.WaitGroup
stopCalling atomic.Int32
callers sync.WaitGroup
)
for i := 0; i < 5; i++ {
callers.Add(1)
closeRelay.Add(1)
go func() {
defer callers.Done()
calls := 0
for stopCalling.Load() == 0 {
testutils.CallEcho(s2, ts.HostPort(), "s1", nil)
calls++
if calls == 5 {
closeRelay.Done()
}
}
}()
}
closeRelay.Wait()
// Close the relay, wait for it to close.
ts.Relay().Close()
closed := testutils.WaitFor(time.Second, func() bool {
return ts.Relay().State() == ChannelClosed
})
assert.True(t, closed, "Relay did not close within timeout")
// Now stop all calls, and wait for the calling goroutine to end.
stopCalling.Inc()
callers.Wait()
})
}
func TestTimeoutCallsThenClose(t *testing.T) {
// TODO: enable framepool checks
// Test needs at least 2 CPUs to trigger race conditions.
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(2))
opts := serviceNameOpts("s1").
SetRelayOnly().
DisableLogVerification()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
s1 := ts.Server()
s2 := ts.NewServer(serviceNameOpts("s2").DisableLogVerification())
unblockEcho := make(chan struct{})
testutils.RegisterEcho(s1, func() {
<-unblockEcho
})
ctx, cancel := NewContext(testutils.Timeout(100 * time.Millisecond))
defer cancel()
var callers sync.WaitGroup
for i := 0; i < 100; i++ {
callers.Add(1)
go func() {
defer callers.Done()
raw.Call(ctx, s2, ts.HostPort(), "s1", "echo", nil, nil)
}()
}
close(unblockEcho)
// Wait for all the callers to end
callers.Wait()
})
}
func TestLargeTimeoutsAreClamped(t *testing.T) {
const (
clampTTL = time.Millisecond
longTTL = time.Minute
)
opts := serviceNameOpts("echo-service").
SetRelayOnly().
SetCheckFramePooling().
SetRelayMaxTimeout(clampTTL).
DisableLogVerification() // handler returns after deadline
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
srv := ts.Server()
client := ts.NewClient(nil)
unblock := make(chan struct{})
defer close(unblock) // let server shut down cleanly
testutils.RegisterFunc(srv, "echo", func(ctx context.Context, args *raw.Args) (*raw.Res, error) {
now := time.Now()
deadline, ok := ctx.Deadline()
assert.True(t, ok, "Expected deadline to be set in handler.")
assert.True(t, deadline.Sub(now) <= clampTTL, "Expected relay to clamp TTL sent to backend.")
<-unblock
return &raw.Res{Arg2: args.Arg2, Arg3: args.Arg3}, nil
})
done := make(chan struct{})
go func() {
ctx, cancel := NewContext(longTTL)
defer cancel()
_, _, _, err := raw.Call(ctx, client, ts.HostPort(), "echo-service", "echo", nil, nil)
require.Error(t, err)
code := GetSystemErrorCode(err)
assert.Equal(t, ErrCodeTimeout, code)
close(done)
}()
// This test is very sensitive to system noise, where a spike of latency in the relay (e.g. caused by load)
// is able to cause the client call to timeout, making this test prone to false positives. As such, we
// can't time out too close to clampTTL, but instead check that we don't time out after longTTL/2. This might
// be a bit generous, but should be sufficient for our purposes here.
select {
case <-time.After(testutils.Timeout(longTTL / 2)):
t.Fatal("Failed to clamp timeout.")
case <-done:
}
})
}
// TestRelayConcurrentCalls makes many concurrent calls and ensures that
// we don't try to reuse any frames once they've been released.
func TestRelayConcurrentCalls(t *testing.T) {
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
server := benchmark.NewServer(
benchmark.WithNoLibrary(),
benchmark.WithServiceName("s1"),
)
defer server.Close()
ts.RelayHost().Add("s1", server.HostPort())
client := benchmark.NewClient([]string{ts.HostPort()},
benchmark.WithNoDurations(),
// TODO(prashant): Enable once we have control over concurrency with NoLibrary.
// benchmark.WithNoLibrary(),
benchmark.WithNumClients(20),
benchmark.WithServiceName("s1"),
benchmark.WithTimeout(time.Minute),
)
defer client.Close()
require.NoError(t, client.Warmup(), "Client warmup failed")
_, err := client.RawCall(1000)
assert.NoError(t, err, "RawCalls failed")
})
}
// Ensure that any connections created in the relay path send the ephemeral
// host:port.
func TestRelayOutgoingConnectionsEphemeral(t *testing.T) {
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
s2 := ts.NewServer(serviceNameOpts("s2"))
testutils.RegisterFunc(s2, "echo", func(ctx context.Context, args *raw.Args) (*raw.Res, error) {
assert.True(t, CurrentCall(ctx).RemotePeer().IsEphemeral,
"Connections created for the relay should send ephemeral host:port header")
return &raw.Res{
Arg2: args.Arg2,
Arg3: args.Arg3,
}, nil
})
require.NoError(t, testutils.CallEcho(ts.Server(), ts.HostPort(), "s2", nil), "CallEcho failed")
})
}
func TestRelayHandleLocalCall(t *testing.T) {
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
SetRelayLocal("relay", "tchannel", "test").
// We make a call to "test" for an unknown method.
AddLogFilter("Couldn't find handler.", 1)
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
s2 := ts.NewServer(serviceNameOpts("s2"))
testutils.RegisterEcho(s2, nil)
client := ts.NewClient(nil)
testutils.AssertEcho(t, client, ts.HostPort(), "s2")
testutils.RegisterEcho(ts.Relay(), nil)
testutils.AssertEcho(t, client, ts.HostPort(), "relay")
// Sould get a bad request for "test" since the channel does not handle it.
err := testutils.CallEcho(client, ts.HostPort(), "test", nil)
assert.Equal(t, ErrCodeBadRequest, GetSystemErrorCode(err), "Expected BadRequest for test")
// But an unknown service causes declined
err = testutils.CallEcho(client, ts.HostPort(), "unknown", nil)
assert.Equal(t, ErrCodeDeclined, GetSystemErrorCode(err), "Expected Declined for unknown")
calls := relaytest.NewMockStats()
calls.Add(client.ServiceName(), "s2", "echo").Succeeded().End()
calls.Add(client.ServiceName(), "unknown", "echo").Failed("relay-declined").End()
ts.AssertRelayStats(calls)
})
}
func TestRelayHandleLargeLocalCall(t *testing.T) {
// TODO: enablle framepool checks
opts := testutils.NewOpts().SetRelayOnly().
SetRelayLocal("relay").
AddLogFilter("Received fragmented callReq", 1).
// Expect 4 callReqContinues for 256 kb payload that we cannot relay.
AddLogFilter("Failed to relay frame.", 4)
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
client := ts.NewClient(nil)
testutils.RegisterEcho(ts.Relay(), nil)
// This large call should fail with a bad request.
err := testutils.CallEcho(client, ts.HostPort(), "relay", &raw.Args{
Arg2: testutils.RandBytes(128 * 1024),
Arg3: testutils.RandBytes(128 * 1024),
})
if assert.Equal(t, ErrCodeBadRequest, GetSystemErrorCode(err), "Expected BadRequest for large call to relay") {
assert.Contains(t, err.Error(), "cannot receive fragmented calls")
}
// We may get an error before the call is finished flushing.
// Do a ping to ensure everything has been flushed.
ctx, cancel := NewContext(time.Second)
defer cancel()
require.NoError(t, client.Ping(ctx, ts.HostPort()), "Ping failed")
})
}
func TestRelayMakeOutgoingCall(t *testing.T) {
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
svr1 := ts.Relay()
svr2 := ts.NewServer(testutils.NewOpts().SetServiceName("svc2"))
testutils.RegisterEcho(svr2, nil)
sizes := []int{128, 1024, 128 * 1024}
for _, size := range sizes {
t.(*testing.T).Run(fmt.Sprintf("size=%d", size), func(t *testing.T) {
err := testutils.CallEcho(svr1, ts.HostPort(), "svc2", &raw.Args{
Arg2: testutils.RandBytes(size),
Arg3: testutils.RandBytes(size),
})
assert.NoError(t, err, "Echo with size %v failed", size)
})
}
})
}
func TestRelayInboundConnContext(t *testing.T) {
rh := relaytest.NewStubRelayHost()
rh.SetFrameFn(func(f relay.CallFrame, conn *relay.Conn) {
// Verify that the relay gets the base context set in the server's ConnContext
assert.Equal(t, "bar", conn.Context.Value("foo"), "Unexpected value set in base context")
})
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
SetRelayHost(rh).
SetConnContext(func(ctx context.Context, conn net.Conn) context.Context {
return context.WithValue(ctx, "foo", "bar")
})
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
rly := ts.Relay()
svr := ts.Server()
testutils.RegisterEcho(svr, nil)
client := testutils.NewClient(t, nil)
testutils.AssertEcho(t, client, rly.PeerInfo().HostPort, ts.ServiceName())
})
}
func TestRelayContextInheritsFromOutboundConnection(t *testing.T) {
rh := relaytest.NewStubRelayHost()
rh.SetFrameFn(func(f relay.CallFrame, conn *relay.Conn) {
// Verify that the relay gets the base context set by the outbound connection to the caller
assert.Equal(t, "bar", conn.Context.Value("foo"), "Unexpected value set in base context")
})
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
SetRelayHost(rh)
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
rly := ts.Relay()
callee := ts.Server()
testutils.RegisterEcho(callee, nil)
caller := ts.NewServer(testutils.NewOpts())
testutils.RegisterEcho(caller, nil)
baseCtx := context.WithValue(context.Background(), "foo", "bar")
ctx, cancel := NewContextBuilder(time.Second).SetConnectBaseContext(baseCtx).Build()
defer cancel()
require.NoError(t, rly.Ping(ctx, caller.PeerInfo().HostPort))
testutils.AssertEcho(t, caller, ts.HostPort(), ts.ServiceName())
})
}
func TestRelayConnection(t *testing.T) {
var errTest = errors.New("test")
var gotConn *relay.Conn
getHost := func(_ relay.CallFrame, conn *relay.Conn) (string, error) {
gotConn = conn
return "", errTest
}
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
SetRelayHost(relaytest.HostFunc(getHost))
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
getConn := func(ch *Channel, outbound bool) ConnectionRuntimeState {
state := ch.IntrospectState(nil)
peer, ok := state.RootPeers[ts.HostPort()]
require.True(t, ok, "Failed to find peer for relay")
conns := peer.InboundConnections
if outbound {
conns = peer.OutboundConnections
}
require.Len(t, conns, 1, "Expect single connection from client to relay")
return conns[0]
}
// Create a client that is listening so we can set the expected host:port.
client := ts.NewClient(nil)
err := testutils.CallEcho(client, ts.HostPort(), ts.ServiceName(), nil)
require.Error(t, err, "Expected CallEcho to fail")
assert.Contains(t, err.Error(), errTest.Error(), "Unexpected error")
wantConn := &relay.Conn{
RemoteAddr: getConn(client, true /* outbound */).LocalHostPort,
RemoteProcessName: client.PeerInfo().ProcessName,
IsOutbound: false,
Context: context.Background(),
}
assert.Equal(t, wantConn, gotConn, "Unexpected remote addr")
// Verify something similar with a listening channel, ensuring that
// we're not using the host:port of the listening server, but the
// host:port of the outbound TCP connection.
listeningC := ts.NewServer(nil)
err = testutils.CallEcho(listeningC, ts.HostPort(), ts.ServiceName(), nil)
require.Error(t, err, "Expected CallEcho to fail")
assert.Contains(t, err.Error(), errTest.Error(), "Unexpected error")
connHostPort := getConn(listeningC, true /* outbound */).LocalHostPort
assert.NotEqual(t, connHostPort, listeningC.PeerInfo().HostPort, "Ensure connection host:port is not listening host:port")
wantConn = &relay.Conn{
RemoteAddr: connHostPort,
RemoteProcessName: listeningC.PeerInfo().ProcessName,
Context: context.Background(),
}
assert.Equal(t, wantConn, gotConn, "Unexpected remote addr")
// Connections created when relaying hide the relay host:port to ensure
// services don't send calls back over that same connection. However,
// this is what happens in the hyperbahn emulation case, so create
// an explicit connection to a new listening channel.
listeningHBSvc := ts.NewServer(nil)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// Ping to ensure the connection has been added to peers on both sides.
err = ts.Relay().Ping(ctx, listeningHBSvc.PeerInfo().HostPort)
require.NoError(t, err, "Failed to connect from relay to listening host:port")
// Now when listeningHBSvc makes a call, it should use the above connection.
err = testutils.CallEcho(listeningHBSvc, ts.HostPort(), ts.ServiceName(), nil)
require.Error(t, err, "Expected CallEcho to fail")
assert.Contains(t, err.Error(), errTest.Error(), "Unexpected error")
// We expect an inbound connection on listeningHBSvc.
connHostPort = getConn(listeningHBSvc, false /* outbound */).LocalHostPort
wantConn = &relay.Conn{
RemoteAddr: connHostPort,
RemoteProcessName: listeningHBSvc.PeerInfo().ProcessName,
IsOutbound: true, // outbound connection according to relay.
Context: context.Background(),
}
assert.Equal(t, wantConn, gotConn, "Unexpected remote addr")
})
}
func TestRelayConnectionClosed(t *testing.T) {
protocolErr := NewSystemError(ErrCodeProtocol, "invalid service name")
getHost := func(relay.CallFrame, *relay.Conn) (string, error) {
return "", protocolErr
}
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
SetRelayHost(relaytest.HostFunc(getHost))
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
// The client receives a protocol error which causes the following logs.
opts := testutils.NewOpts().
AddLogFilter("Peer reported protocol error", 1).
AddLogFilter("Connection error", 1)
client := ts.NewClient(opts)
err := testutils.CallEcho(client, ts.HostPort(), ts.ServiceName(), nil)
assert.Equal(t, protocolErr, err, "Unexpected error on call")
closedAll := testutils.WaitFor(time.Second, func() bool {
return ts.Relay().IntrospectNumConnections() == 0
})
assert.True(t, closedAll, "Relay should close client connection")
})
}
func TestRelayUsesRootPeers(t *testing.T) {
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
testutils.RegisterEcho(ts.Server(), nil)
client := testutils.NewClient(t, nil)
err := testutils.CallEcho(client, ts.HostPort(), ts.ServiceName(), nil)
assert.NoError(t, err, "Echo failed")
assert.Len(t, ts.Relay().Peers().Copy(), 0, "Peers should not be modified by relay")
})
}
// Ensure that if the relay recieves a call on a connection that is not active,
// it declines the call, and increments a relay-client-conn-inactive stat.
func TestRelayRejectsDuringClose(t *testing.T) {
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
AddLogFilter("Failed to relay frame.", 1, "error", "incoming connection is not active: connectionStartClose")
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
gotCall := make(chan struct{})
block := make(chan struct{})
testutils.RegisterEcho(ts.Server(), func() {
close(gotCall)
<-block
})
client := ts.NewClient(nil)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
testutils.AssertEcho(t, client, ts.HostPort(), ts.ServiceName())
}()
<-gotCall
// Close the relay so that it stops accepting more calls.
ts.Relay().Close()
err := testutils.CallEcho(client, ts.HostPort(), ts.ServiceName(), nil)
require.Error(t, err, "Expect call to fail after relay is shutdown")
assert.Contains(t, err.Error(), "incoming connection is not active")
close(block)
wg.Wait()
// We have a successful call that ran in the goroutine
// and a failed call that we just checked the error on.
calls := relaytest.NewMockStats()
calls.Add(client.PeerInfo().ServiceName, ts.ServiceName(), "echo").
Succeeded().End()
calls.Add(client.PeerInfo().ServiceName, ts.ServiceName(), "echo").
// No peer is set since we rejected the call before selecting one.
Failed("relay-client-conn-inactive").End()
ts.AssertRelayStats(calls)
})
}
func TestRelayRateLimitDrop(t *testing.T) {
getHost := func(relay.CallFrame, *relay.Conn) (string, error) {
return "", relay.RateLimitDropError{}
}
opts := testutils.NewOpts().
SetRelayOnly().
SetCheckFramePooling().
SetRelayHost(relaytest.HostFunc(getHost))
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
var gotCall bool
testutils.RegisterEcho(ts.Server(), func() {
gotCall = true
})
client := ts.NewClient(nil)
var wg sync.WaitGroup
wg.Add(1)
go func() {
// We want to use a low timeout here since the test waits for this
// call to timeout.
ctx, cancel := NewContext(testutils.Timeout(100 * time.Millisecond))
defer cancel()
_, _, _, err := raw.Call(ctx, client, ts.HostPort(), ts.ServiceName(), "echo", nil, nil)
require.Equal(t, ErrTimeout, err, "Expected CallEcho to fail")
defer wg.Done()
}()
wg.Wait()
assert.False(t, gotCall, "Server should not receive a call")
calls := relaytest.NewMockStats()
calls.Add(client.PeerInfo().ServiceName, ts.ServiceName(), "echo").
Failed("relay-dropped").End()
ts.AssertRelayStats(calls)
})
}
// Test that a stalled connection to a single server does not block all calls
// from that server, and we have stats to capture that this is happening.
func TestRelayStalledConnection(t *testing.T) {
// TODO(ablackmon): Debug why this is flaky in github
if os.Getenv("GITHUB_WORKFLOW") != "" {
t.Skip("skipping test flaky in github actions.")
}
// TODO: enable framepool checks
opts := testutils.NewOpts().
AddLogFilter("Dropping call due to slow connection.", 1, "sendChCapacity", "32").
SetSendBufferSize(32). // We want to hit the buffer size earlier, but also ensure we're only dropping once the sendCh is full.
SetServiceName("s1").
SetRelayOnly()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
s2 := ts.NewServer(testutils.NewOpts().SetServiceName("s2"))
testutils.RegisterEcho(s2, nil)
stall := make(chan struct{})
stallComplete := make(chan struct{})
stallHandler := func(ctx context.Context, call *InboundCall) {
<-stall
raw.ReadArgs(call)
close(stallComplete)
}
ts.Register(HandlerFunc(stallHandler), "echo")
ctx, cancel := NewContext(testutils.Timeout(300 * time.Millisecond))
defer cancel()
client := ts.NewClient(nil)
call, err := client.BeginCall(ctx, ts.HostPort(), ts.ServiceName(), "echo", nil)
require.NoError(t, err, "BeginCall failed")
writer, err := call.Arg2Writer()
require.NoError(t, err, "Arg2Writer failed")
go io.Copy(writer, testreader.Looper([]byte("test")))
// Try to read the response which might get an error.
readDone := make(chan struct{})
go func() {
defer close(readDone)
_, err := call.Response().Arg2Reader()
if assert.Error(t, err, "Expected error while reading") {
assert.Contains(t, err.Error(), "frame was not sent to remote side")
}
}()
// Wait for the reader to error out.
select {
case <-time.After(testutils.Timeout(10 * time.Second)):
t.Fatalf("Test timed out waiting for reader to fail")
case <-readDone:
}
// We should be able to make calls to s2 even if s1 is stalled.
testutils.AssertEcho(t, client, ts.HostPort(), "s2")
// Verify the sendCh is full, and the buffers are utilized.
state := ts.Relay().IntrospectState(&IntrospectionOptions{})
connState := state.RootPeers[ts.Server().PeerInfo().HostPort].OutboundConnections[0]
assert.Equal(t, 32, connState.SendChCapacity, "unexpected SendChCapacity")
assert.NotZero(t, connState.SendChQueued, "unexpected SendChQueued")
assert.NotZero(t, connState.SendBufferUsage, "unexpected SendBufferUsage")
assert.NotZero(t, connState.SendBufferSize, "unexpected SendBufferSize")
// Cancel the call and unblock the stall handler.
cancel()
close(stall)
// The server channel will not close until the stall handler receives
// an error. Since we don't propagate cancels, the handler will keep
// trying to read arguments till the timeout.
select {
case <-stallComplete:
case <-time.After(testutils.Timeout(300 * time.Millisecond)):
t.Fatalf("Stall handler did not complete")
}
calls := relaytest.NewMockStats()
calls.Add(client.PeerInfo().ServiceName, ts.ServiceName(), "echo").
Failed("relay-dest-conn-slow").End()
calls.Add(client.PeerInfo().ServiceName, "s2", "echo").
Succeeded().End()
ts.AssertRelayStats(calls)
})
}
// Test that a stalled connection to the client does not cause stuck calls
// See https://github.com/uber/tchannel-go/issues/700 for more info.
func TestRelayStalledClientConnection(t *testing.T) {
// This needs to be large enough to fill up the client TCP buffer.
const _calls = 100
// TODO: enable framepool checks
opts := testutils.NewOpts().
// Expect errors from dropped frames.
AddLogFilter("Dropping call due to slow connection.", _calls).
SetSendBufferSize(10). // We want to hit the buffer size earlier.
SetServiceName("s1").
SetRelayOnly()
testutils.WithTestServer(t, opts, func(t testing.TB, ts *testutils.TestServer) {
// Track when the server receives calls
gotCall := make(chan struct{}, _calls)
testutils.RegisterEcho(ts.Server(), func() {
gotCall <- struct{}{}
})
// Create a frame relay that will block all client inbound frames.
unblockClientInbound := make(chan struct{})
blockerHostPort, relayCancel := testutils.FrameRelay(t, ts.HostPort(), func(outgoing bool, f *Frame) *Frame {
if !outgoing && f.Header.ID > 1 {
// Block all inbound frames except the initRes
<-unblockClientInbound
}
return f
})
defer relayCancel()
defer close(unblockClientInbound)
client := ts.NewClient(nil)
ctx, cancel := NewContext(testutils.Timeout(time.Second))
defer cancel()
var calls []*OutboundCall
// Data to fit one frame fully, but large enough that a number of these frames will fill
// all the buffers and cause the relay to drop the response frame. Buffers are:
// 1. Relay's sendCh on the connection to the client (set to 10 frames explicitly)
// 2. Relay's TCP send buffer for the connection to the client.
// 3. Client's TCP receive buffer on the connection to the relay.
data := bytes.Repeat([]byte("test"), 256*60)
for i := 0; i < _calls; i++ {
call, err := client.BeginCall(ctx, blockerHostPort, ts.ServiceName(), "echo", nil)
require.NoError(t, err, "BeginCall failed")
require.NoError(t, NewArgWriter(call.Arg2Writer()).Write(nil), "arg2 write failed")
require.NoError(t, NewArgWriter(call.Arg3Writer()).Write(data), "arg2 write failed")
// Wait for server to receive the call
<-gotCall
calls = append(calls, call)
}
// Wait for all calls to end on the relay, and ensure we got failures from the slow client.
stats := ts.RelayHost().Stats()
stats.WaitForEnd()
assert.Contains(t, stats.Map(), "testService-client->s1::echo.failed-relay-source-conn-slow", "Expect at least 1 failed call due to slow client")
// We don't read the responses, as we want the client's TCP buffers to fill up
// and the relay to drop calls. However, we should unblock the client reader
// to make sure the client channel can close.
// Unblock the client so it can close.
cancel()
for _, call := range calls {
require.Error(t, NewArgReader(call.Response().Arg2Reader()).Read(&data), "should fail to read response")
}
})
}
// Test that a corrupted callRes frame results in log emission. We set up the following:
//
// client <-> relay <-> man-in-the-middle (MITM) relay <-> server
//
// The MITM relay is configured to intercept and corrupt response frames (through truncation)
// sent back from the server, and forward them back to the relay, where it is checked for errors.
func TestRelayCorruptedCallResFrame(t *testing.T) {
// TODO: Debug why this is flaky in github
if os.Getenv("GITHUB_WORKFLOW") != "" {
t.Skip("skipping test flaky in github actions.")
}
opts := testutils.NewOpts().
// Expect errors from corrupted callRes frames.
AddLogFilter("Malformed callRes frame.", 1).