-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_test.go
1421 lines (1235 loc) · 37.2 KB
/
rpc_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 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package rpc_test
import (
"context"
"encoding/json"
"fmt"
"net"
"reflect"
"regexp"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/rpc"
"github.com/juju/juju/rpc/jsoncodec"
"github.com/juju/juju/rpc/rpcreflect"
"github.com/juju/juju/testing"
)
var logger = loggo.GetLogger("juju.rpc")
type rpcSuite struct {
testing.BaseSuite
}
var _ = gc.Suite(&rpcSuite{})
type callInfo struct {
rcvr interface{}
method string
arg interface{}
}
type callError callInfo
func (e *callError) Error() string {
return fmt.Sprintf("error calling %s", e.method)
}
type stringVal struct {
Val string
}
type Root struct {
mu sync.Mutex
conn *rpc.Conn
calls []*callInfo
returnErr bool
simple map[string]*SimpleMethods
delayed map[string]*DelayedMethods
errorInst *ErrorMethods
contextInst *ContextMethods
}
func (r *Root) callError(rcvr interface{}, name string, arg interface{}) error {
if r.returnErr {
return &callError{rcvr, name, arg}
}
return nil
}
func (r *Root) SimpleMethods(id string) (*SimpleMethods, error) {
r.mu.Lock()
defer r.mu.Unlock()
if a := r.simple[id]; a != nil {
return a, nil
}
return nil, fmt.Errorf("unknown SimpleMethods id")
}
func (r *Root) DelayedMethods(id string) (*DelayedMethods, error) {
r.mu.Lock()
defer r.mu.Unlock()
if a := r.delayed[id]; a != nil {
return a, nil
}
return nil, fmt.Errorf("unknown DelayedMethods id")
}
func (r *Root) ErrorMethods(id string) (*ErrorMethods, error) {
if r.errorInst == nil {
return nil, fmt.Errorf("no error methods")
}
return r.errorInst, nil
}
func (r *Root) ContextMethods(id string) (*ContextMethods, error) {
if r.contextInst == nil {
return nil, fmt.Errorf("no context methods")
}
return r.contextInst, nil
}
func (r *Root) Discard1() {}
func (r *Root) Discard2(id string) error { return nil }
func (r *Root) Discard3(id string) int { return 0 }
func (r *Root) CallbackMethods(string) (*CallbackMethods, error) {
return &CallbackMethods{r}, nil
}
func (r *Root) InterfaceMethods(id string) (InterfaceMethods, error) {
logger.Infof("interface methods called")
m, err := r.SimpleMethods(id)
if err != nil {
return nil, err
}
return m, nil
}
type InterfaceMethods interface {
Call1r1e(s stringVal) (stringVal, error)
}
type ChangeAPIMethods struct {
r *Root
}
func (r *Root) ChangeAPIMethods(string) (*ChangeAPIMethods, error) {
return &ChangeAPIMethods{r}, nil
}
func (t *Root) called(rcvr interface{}, method string, arg interface{}) {
t.mu.Lock()
t.calls = append(t.calls, &callInfo{rcvr, method, arg})
t.mu.Unlock()
}
type SimpleMethods struct {
root *Root
id string
}
// Each Call method is named in this standard form:
//
// Call<narg>r<nret><e>
//
// where narg is the number of arguments, nret is the number of returned
// values (not including the error) and e is the letter 'e' if the
// method returns an error.
func (a *SimpleMethods) Call0r0() {
a.root.called(a, "Call0r0", nil)
}
func (a *SimpleMethods) Call0r1() stringVal {
a.root.called(a, "Call0r1", nil)
return stringVal{"Call0r1 ret"}
}
func (a *SimpleMethods) Call0r1e() (stringVal, error) {
a.root.called(a, "Call0r1e", nil)
return stringVal{"Call0r1e ret"}, a.root.callError(a, "Call0r1e", nil)
}
func (a *SimpleMethods) Call0r0e() error {
a.root.called(a, "Call0r0e", nil)
return a.root.callError(a, "Call0r0e", nil)
}
func (a *SimpleMethods) Call1r0(s stringVal) {
a.root.called(a, "Call1r0", s)
}
func (a *SimpleMethods) Call1r1(s stringVal) stringVal {
a.root.called(a, "Call1r1", s)
return stringVal{"Call1r1 ret"}
}
func (a *SimpleMethods) Call1r1e(s stringVal) (stringVal, error) {
a.root.called(a, "Call1r1e", s)
return stringVal{"Call1r1e ret"}, a.root.callError(a, "Call1r1e", s)
}
func (a *SimpleMethods) Call1r0e(s stringVal) error {
a.root.called(a, "Call1r0e", s)
return a.root.callError(a, "Call1r0e", s)
}
func (a *SimpleMethods) SliceArg(struct{ X []string }) stringVal {
return stringVal{"SliceArg ret"}
}
func (a *SimpleMethods) Discard1(int) {}
func (a *SimpleMethods) Discard2(struct{}, struct{}) {}
func (a *SimpleMethods) Discard3() int { return 0 }
func (a *SimpleMethods) Discard4() (_, _ struct{}) { return }
type ContextMethods struct {
root *Root
callContext context.Context
waiting chan struct{}
}
func (c *ContextMethods) Call0(ctx context.Context) error {
c.root.called(c, "Call0", nil)
c.callContext = ctx
return c.checkContext(ctx)
}
func (c *ContextMethods) Call1(ctx context.Context, s stringVal) error {
c.root.called(c, "Call1", s)
c.callContext = ctx
return c.checkContext(ctx)
}
func (c *ContextMethods) Wait(ctx context.Context) error {
c.root.called(c, "Wait", nil)
close(c.waiting)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(testing.LongWait):
return errors.New("expected context to be cancelled")
}
}
func (c *ContextMethods) checkContext(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(testing.ShortWait):
}
return nil
}
type DelayedMethods struct {
ready chan struct{}
done chan string
doneError chan error
}
func (a *DelayedMethods) Delay() (stringVal, error) {
if a.ready != nil {
a.ready <- struct{}{}
}
select {
case s := <-a.done:
return stringVal{s}, nil
case err := <-a.doneError:
return stringVal{}, err
}
}
type ErrorMethods struct {
err error
}
func (e *ErrorMethods) Call() error {
return e.err
}
type CallbackMethods struct {
root *Root
}
type int64val struct {
I int64
}
func (a *CallbackMethods) Factorial(x int64val) (int64val, error) {
if x.I <= 1 {
return int64val{1}, nil
}
var r int64val
err := a.root.conn.Call(rpc.Request{"CallbackMethods", 0, "", "Factorial"}, int64val{x.I - 1}, &r)
if err != nil {
return int64val{}, err
}
return int64val{x.I * r.I}, nil
}
func (a *ChangeAPIMethods) ChangeAPI() {
a.r.conn.Serve(&changedAPIRoot{}, nil, nil)
}
func (a *ChangeAPIMethods) RemoveAPI() {
a.r.conn.Serve(nil, nil, nil)
}
type changedAPIRoot struct{}
func (r *changedAPIRoot) NewlyAvailable(string) (newlyAvailableMethods, error) {
return newlyAvailableMethods{}, nil
}
type newlyAvailableMethods struct{}
func (newlyAvailableMethods) NewMethod() stringVal {
return stringVal{"new method result"}
}
type VariableMethods1 struct {
sm *SimpleMethods
}
func (vm *VariableMethods1) Call0r1() stringVal {
return vm.sm.Call0r1()
}
type VariableMethods2 struct {
sm *SimpleMethods
}
func (vm *VariableMethods2) Call1r1(s stringVal) stringVal {
return vm.sm.Call1r1(s)
}
type RestrictedMethods struct {
InterfaceMethods
}
type CustomRoot struct {
root *Root
}
type wrapper func(*SimpleMethods) reflect.Value
type customMethodCaller struct {
wrap wrapper
root *Root
objMethod rpcreflect.ObjMethod
expectedType reflect.Type
}
func (c customMethodCaller) ParamsType() reflect.Type {
return c.objMethod.Params
}
func (c customMethodCaller) ResultType() reflect.Type {
return c.objMethod.Result
}
func (c customMethodCaller) Call(_ context.Context, objId string, arg reflect.Value) (reflect.Value, error) {
sm, err := c.root.SimpleMethods(objId)
if err != nil {
return reflect.Value{}, err
}
obj := c.wrap(sm)
if reflect.TypeOf(obj) != c.expectedType {
logger.Errorf("got the wrong type back, expected %s got %T", c.expectedType, obj)
}
logger.Debugf("calling: %T %v %#v", obj, obj, c.objMethod)
return c.objMethod.Call(context.TODO(), obj, arg)
}
func (cc *CustomRoot) Kill() {
}
func (cc *CustomRoot) FindMethod(
rootMethodName string, version int, objMethodName string,
) (
rpcreflect.MethodCaller, error,
) {
logger.Debugf("got to FindMethod: %q %d %q", rootMethodName, version, objMethodName)
if rootMethodName != "MultiVersion" {
return nil, &rpcreflect.CallNotImplementedError{
RootMethod: rootMethodName,
}
}
var goType reflect.Type
var wrap wrapper
switch version {
case 0:
goType = reflect.TypeOf((*VariableMethods1)(nil))
wrap = func(sm *SimpleMethods) reflect.Value {
return reflect.ValueOf(&VariableMethods1{sm})
}
case 1:
goType = reflect.TypeOf((*VariableMethods2)(nil))
wrap = func(sm *SimpleMethods) reflect.Value {
return reflect.ValueOf(&VariableMethods2{sm})
}
case 2:
goType = reflect.TypeOf((*RestrictedMethods)(nil))
wrap = func(sm *SimpleMethods) reflect.Value {
methods := &RestrictedMethods{InterfaceMethods: sm}
return reflect.ValueOf(methods)
}
default:
return nil, &rpcreflect.CallNotImplementedError{
RootMethod: rootMethodName,
Version: version,
}
}
logger.Debugf("found type: %s", goType)
objType := rpcreflect.ObjTypeOf(goType)
objMethod, err := objType.Method(objMethodName)
if err != nil {
return nil, &rpcreflect.CallNotImplementedError{
RootMethod: rootMethodName,
Version: version,
Method: objMethodName,
}
}
return customMethodCaller{
objMethod: objMethod,
root: cc.root,
wrap: wrap,
expectedType: goType,
}, nil
}
func SimpleRoot() *Root {
root := &Root{
simple: make(map[string]*SimpleMethods),
}
root.simple["a99"] = &SimpleMethods{root: root, id: "a99"}
return root
}
func (*rpcSuite) TestRPC(c *gc.C) {
root := SimpleRoot()
client, _, srvDone, serverNotifier := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
for narg := 0; narg < 2; narg++ {
for nret := 0; nret < 2; nret++ {
for nerr := 0; nerr < 2; nerr++ {
retErr := nerr != 0
p := testCallParams{
client: client,
serverNotifier: serverNotifier,
entry: "SimpleMethods",
narg: narg,
nret: nret,
retErr: retErr,
testErr: false,
}
root.testCall(c, p)
if retErr {
p.testErr = true
root.testCall(c, p)
}
}
}
}
}
func callName(narg, nret int, retErr bool) string {
e := ""
if retErr {
e = "e"
}
return fmt.Sprintf("Call%dr%d%s", narg, nret, e)
}
type testCallParams struct {
// client holds the client-side of the rpc connection that
// will be used to make the call.
client *rpc.Conn
// serverNotifier holds the notifier for the server side.
serverNotifier *notifier
// entry holds the top-level type that will be invoked
// (e.g. "SimpleMethods").
entry string
// narg holds the number of arguments accepted by the
// call (0 or 1).
narg int
// nret holds the number of values returned by the
// call (0 or 1).
nret int
// retErr specifies whether the call returns an error.
retErr bool
// testErr specifies whether the call should be made to return an error.
testErr bool
// version specifies what version of the interface to call, defaults to 0.
version int
}
// request returns the RPC request for the test call.
func (p testCallParams) request() rpc.Request {
return rpc.Request{
Type: p.entry,
Version: p.version,
Id: "a99",
Action: callName(p.narg, p.nret, p.retErr),
}
}
// error message returns the error message that the test call
// should return if it returns an error.
func (p testCallParams) errorMessage() string {
return fmt.Sprintf("error calling %s", p.request().Action)
}
func (root *Root) testCall(c *gc.C, args testCallParams) {
args.serverNotifier.reset()
root.calls = nil
root.returnErr = args.testErr
c.Logf("test call %s", args.request().Action)
var response stringVal
err := args.client.Call(args.request(), stringVal{"arg"}, &response)
switch {
case args.retErr && args.testErr:
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: args.errorMessage(),
})
c.Assert(response, gc.Equals, stringVal{})
case args.nret > 0:
c.Check(response, gc.Equals, stringVal{args.request().Action + " ret"})
}
if !args.testErr {
c.Check(err, jc.ErrorIsNil)
}
// Check that the call was actually made, the right
// parameters were received and the right result returned.
root.mu.Lock()
defer root.mu.Unlock()
root.assertCallMade(c, args)
root.assertServerNotified(c, args, args.client.ClientRequestID())
}
func (root *Root) assertCallMade(c *gc.C, p testCallParams) {
expectCall := callInfo{
rcvr: root.simple["a99"],
method: p.request().Action,
}
if p.narg > 0 {
expectCall.arg = stringVal{"arg"}
}
c.Assert(root.calls, gc.HasLen, 1)
c.Assert(*root.calls[0], gc.Equals, expectCall)
}
// assertServerNotified asserts that the right server notifications
// were made for the given test call parameters. The id of the request
// is held in requestId.
func (root *Root) assertServerNotified(c *gc.C, p testCallParams, requestId uint64) {
// Test that there was a notification for the request.
c.Assert(p.serverNotifier.serverRequests, gc.HasLen, 1)
serverReq := p.serverNotifier.serverRequests[0]
c.Assert(serverReq.hdr, gc.DeepEquals, rpc.Header{
RequestId: requestId,
Request: p.request(),
Version: 1,
})
if p.narg > 0 {
c.Assert(serverReq.body, gc.Equals, stringVal{"arg"})
} else {
c.Assert(serverReq.body, gc.Equals, struct{}{})
}
// Test that there was a notification for the reply.
c.Assert(p.serverNotifier.serverReplies, gc.HasLen, 1)
serverReply := p.serverNotifier.serverReplies[0]
c.Assert(serverReply.req, gc.Equals, p.request())
if p.retErr && p.testErr || p.nret == 0 {
c.Assert(serverReply.body, gc.Equals, struct{}{})
} else {
c.Assert(serverReply.body, gc.Equals, stringVal{p.request().Action + " ret"})
}
if p.retErr && p.testErr {
c.Assert(serverReply.hdr, gc.Equals, rpc.Header{
RequestId: requestId,
Error: p.errorMessage(),
Version: 1,
})
} else {
c.Assert(serverReply.hdr, gc.Equals, rpc.Header{
RequestId: requestId,
Version: 1,
})
}
}
func (*rpcSuite) TestInterfaceMethods(c *gc.C) {
root := SimpleRoot()
client, _, srvDone, serverNotifier := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
p := testCallParams{
client: client,
serverNotifier: serverNotifier,
entry: "InterfaceMethods",
narg: 1,
nret: 1,
retErr: true,
testErr: false,
}
root.testCall(c, p)
p.testErr = true
root.testCall(c, p)
// Call0r0 is defined on the underlying SimpleMethods, but is not
// exposed at the InterfaceMethods level, so this call should fail with
// CodeNotImplemented.
var r stringVal
err := client.Call(rpc.Request{"InterfaceMethods", 0, "a99", "Call0r0"}, stringVal{"arg"}, &r)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "no such request - method InterfaceMethods.Call0r0 is not implemented",
Code: rpc.CodeNotImplemented,
})
}
func (*rpcSuite) TestCustomRootV0(c *gc.C) {
root := &CustomRoot{SimpleRoot()}
client, _, srvDone, serverNotifier := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
// V0 of MultiVersion implements only VariableMethods1.Call0r1.
p := testCallParams{
client: client,
serverNotifier: serverNotifier,
entry: "MultiVersion",
version: 0,
narg: 0,
nret: 1,
retErr: false,
testErr: false,
}
root.root.testCall(c, p)
// Call1r1 is exposed in version 1, but not in version 0.
var r stringVal
err := client.Call(rpc.Request{"MultiVersion", 0, "a99", "Call1r1"}, stringVal{"arg"}, &r)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "no such request - method MultiVersion.Call1r1 is not implemented",
Code: rpc.CodeNotImplemented,
})
}
func (*rpcSuite) TestCustomRootV1(c *gc.C) {
root := &CustomRoot{SimpleRoot()}
client, _, srvDone, serverNotifier := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
// V1 of MultiVersion implements only VariableMethods2.Call1r1.
p := testCallParams{
client: client,
serverNotifier: serverNotifier,
entry: "MultiVersion",
version: 1,
narg: 1,
nret: 1,
retErr: false,
testErr: false,
}
root.root.testCall(c, p)
// Call0r1 is exposed in version 0, but not in version 1.
var r stringVal
err := client.Call(rpc.Request{"MultiVersion", 1, "a99", "Call0r1"}, nil, &r)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "no such request - method MultiVersion(1).Call0r1 is not implemented",
Code: rpc.CodeNotImplemented,
})
}
func (*rpcSuite) TestCustomRootV2(c *gc.C) {
root := &CustomRoot{SimpleRoot()}
client, _, srvDone, serverNotifier := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
p := testCallParams{
client: client,
serverNotifier: serverNotifier,
entry: "MultiVersion",
version: 2,
narg: 1,
nret: 1,
retErr: true,
testErr: false,
}
root.root.testCall(c, p)
// By embedding the InterfaceMethods inside a concrete
// RestrictedMethods type, we actually only expose the methods defined
// in InterfaceMethods.
var r stringVal
err := client.Call(rpc.Request{"MultiVersion", 2, "a99", "Call0r1e"}, nil, &r)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: `no such request - method MultiVersion(2).Call0r1e is not implemented`,
Code: rpc.CodeNotImplemented,
})
}
func (*rpcSuite) TestCustomRootUnknownVersion(c *gc.C) {
root := &CustomRoot{SimpleRoot()}
client, _, srvDone, _ := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
var r stringVal
// Unknown version 5
err := client.Call(rpc.Request{"MultiVersion", 5, "a99", "Call0r1"}, nil, &r)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: `unknown version (5) of interface "MultiVersion"`,
Code: rpc.CodeNotImplemented,
})
}
func (*rpcSuite) TestConcurrentCalls(c *gc.C) {
start1 := make(chan string)
start2 := make(chan string)
ready1 := make(chan struct{})
ready2 := make(chan struct{})
root := &Root{
delayed: map[string]*DelayedMethods{
"1": {ready: ready1, done: start1},
"2": {ready: ready2, done: start2},
},
}
client, _, srvDone, _ := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
call := func(id string, done chan<- struct{}) {
var r stringVal
err := client.Call(rpc.Request{"DelayedMethods", 0, id, "Delay"}, nil, &r)
c.Check(err, jc.ErrorIsNil)
c.Check(r.Val, gc.Equals, "return "+id)
done <- struct{}{}
}
done1 := make(chan struct{})
done2 := make(chan struct{})
go call("1", done1)
go call("2", done2)
// Check that both calls are running concurrently.
chanRead(c, ready1, "method 1 ready")
chanRead(c, ready2, "method 2 ready")
// Let the requests complete.
start1 <- "return 1"
start2 <- "return 2"
chanRead(c, done1, "method 1 done")
chanRead(c, done2, "method 2 done")
}
type codedError struct {
m string
code string
}
func (e *codedError) Error() string {
return e.m
}
func (e *codedError) ErrorCode() string {
return e.code
}
func (*rpcSuite) TestErrorCode(c *gc.C) {
root := &Root{
errorInst: &ErrorMethods{&codedError{"message", "code"}},
}
client, _, srvDone, _ := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
err := client.Call(rpc.Request{"ErrorMethods", 0, "", "Call"}, nil, nil)
c.Assert(err, gc.ErrorMatches, `message \(code\)`)
c.Assert(errors.Cause(err).(rpc.ErrorCoder).ErrorCode(), gc.Equals, "code")
}
func (*rpcSuite) TestTransformErrors(c *gc.C) {
root := &Root{
errorInst: &ErrorMethods{&codedError{"message", "code"}},
}
tfErr := func(err error) error {
c.Check(err, gc.NotNil)
if e, ok := err.(*codedError); ok {
return &codedError{
m: "transformed: " + e.m,
code: "transformed: " + e.code,
}
}
return fmt.Errorf("transformed: %v", err)
}
client, _, srvDone, _ := newRPCClientServer(c, root, tfErr, false)
defer closeClient(c, client, srvDone)
// First, we don't transform methods we can't find.
err := client.Call(rpc.Request{"foo", 0, "", "bar"}, nil, nil)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: `unknown object type "foo"`,
Code: rpc.CodeNotImplemented,
})
err = client.Call(rpc.Request{"ErrorMethods", 0, "", "NoMethod"}, nil, nil)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "no such request - method ErrorMethods.NoMethod is not implemented",
Code: rpc.CodeNotImplemented,
})
// We do transform any errors that happen from calling the RootMethod
// and beyond.
err = client.Call(rpc.Request{"ErrorMethods", 0, "", "Call"}, nil, nil)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "transformed: message",
Code: "transformed: code",
})
root.errorInst.err = nil
err = client.Call(rpc.Request{"ErrorMethods", 0, "", "Call"}, nil, nil)
c.Assert(err, jc.ErrorIsNil)
root.errorInst = nil
err = client.Call(rpc.Request{"ErrorMethods", 0, "", "Call"}, nil, nil)
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: "transformed: no error methods",
})
}
func (*rpcSuite) TestServerWaitsForOutstandingCalls(c *gc.C) {
ready := make(chan struct{})
start := make(chan string)
root := &Root{
delayed: map[string]*DelayedMethods{
"1": {
ready: ready,
done: start,
},
},
}
client, _, srvDone, _ := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
done := make(chan struct{})
go func() {
var r stringVal
err := client.Call(rpc.Request{"DelayedMethods", 0, "1", "Delay"}, nil, &r)
c.Check(errors.Cause(err), gc.Equals, rpc.ErrShutdown)
done <- struct{}{}
}()
chanRead(c, ready, "DelayedMethods.Delay ready")
client.Close()
select {
case err := <-srvDone:
c.Fatalf("server returned while outstanding operation in progress: %v", err)
<-done
case <-time.After(25 * time.Millisecond):
}
start <- "xxx"
}
func chanRead(c *gc.C, ch <-chan struct{}, what string) {
select {
case <-ch:
return
case <-time.After(3 * time.Second):
c.Fatalf("timeout on channel read %s", what)
}
}
func (*rpcSuite) TestCompatibility(c *gc.C) {
root := &Root{
simple: make(map[string]*SimpleMethods),
}
a0 := &SimpleMethods{root: root, id: "a0"}
root.simple["a0"] = a0
client, _, srvDone, _ := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
call := func(method string, arg, ret interface{}) (passedArg interface{}) {
root.calls = nil
err := client.Call(rpc.Request{"SimpleMethods", 0, "a0", method}, arg, ret)
c.Assert(err, jc.ErrorIsNil)
c.Assert(root.calls, gc.HasLen, 1)
info := root.calls[0]
c.Assert(info.rcvr, gc.Equals, a0)
c.Assert(info.method, gc.Equals, method)
return info.arg
}
type extra struct {
Val string
Extra string
}
// Extra fields in request and response.
var r extra
arg := call("Call1r1", extra{"x", "y"}, &r)
c.Assert(arg, gc.Equals, stringVal{"x"})
// Nil argument as request.
r = extra{}
arg = call("Call1r1", nil, &r)
c.Assert(arg, gc.Equals, stringVal{})
// Nil argument as response.
arg = call("Call1r1", stringVal{"x"}, nil)
c.Assert(arg, gc.Equals, stringVal{"x"})
// Non-nil argument for no response.
r = extra{}
arg = call("Call1r0", stringVal{"x"}, &r)
c.Assert(arg, gc.Equals, stringVal{"x"})
c.Assert(r, gc.Equals, extra{})
}
func (*rpcSuite) TestBadCall(c *gc.C) {
loggo.GetLogger("juju.rpc").SetLogLevel(loggo.TRACE)
root := &Root{
simple: make(map[string]*SimpleMethods),
}
a0 := &SimpleMethods{root: root, id: "a0"}
root.simple["a0"] = a0
client, _, srvDone, serverNotifier := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
testBadCall(c, client, serverNotifier,
rpc.Request{"BadSomething", 0, "a0", "No"},
`unknown object type "BadSomething"`,
rpc.CodeNotImplemented,
false,
)
testBadCall(c, client, serverNotifier,
rpc.Request{"SimpleMethods", 0, "xx", "No"},
"no such request - method SimpleMethods.No is not implemented",
rpc.CodeNotImplemented,
false,
)
testBadCall(c, client, serverNotifier,
rpc.Request{"SimpleMethods", 0, "xx", "Call0r0"},
`unknown SimpleMethods id`,
"",
true,
)
}
func testBadCall(
c *gc.C,
client *rpc.Conn,
serverNotifier *notifier,
req rpc.Request,
expectedErr string,
expectedErrCode string,
requestKnown bool,
) {
serverNotifier.reset()
err := client.Call(req, nil, nil)
msg := expectedErr
if expectedErrCode != "" {
msg += " (" + expectedErrCode + ")"
}
c.Assert(err, gc.ErrorMatches, regexp.QuoteMeta(msg))
// From docs on ServerRequest:
// If the request was not recognized or there was
// an error reading the body, body will be nil.
var expectBody interface{}
if requestKnown {
expectBody = struct{}{}
}
c.Assert(serverNotifier.serverRequests[0], gc.DeepEquals, requestEvent{
hdr: rpc.Header{
RequestId: client.ClientRequestID(),
Request: req,
Version: 1,
},
body: expectBody,
})
// Test that there was a notification for the server reply.
c.Assert(serverNotifier.serverReplies, gc.HasLen, 1)
serverReply := serverNotifier.serverReplies[0]
c.Assert(serverReply, gc.DeepEquals, replyEvent{
hdr: rpc.Header{
RequestId: client.ClientRequestID(),
Error: expectedErr,
ErrorCode: expectedErrCode,
Version: 1,
},
req: req,
body: struct{}{},
})
}
func (*rpcSuite) TestContinueAfterReadBodyError(c *gc.C) {
root := &Root{
simple: make(map[string]*SimpleMethods),
}
a0 := &SimpleMethods{root: root, id: "a0"}
root.simple["a0"] = a0
client, _, srvDone, _ := newRPCClientServer(c, root, nil, false)
defer closeClient(c, client, srvDone)
var ret stringVal
arg0 := struct {
X map[string]int
}{
X: map[string]int{"hello": 65},
}
err := client.Call(rpc.Request{"SimpleMethods", 0, "a0", "SliceArg"}, arg0, &ret)
c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal object into Go (?:value)|(?:struct field \.X) of type \[\]string`)
err = client.Call(rpc.Request{"SimpleMethods", 0, "a0", "SliceArg"}, arg0, &ret)
c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal object into Go (?:value)|(?:struct field \.X) of type \[\]string`)