forked from dedis/onet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice_test.go
694 lines (603 loc) · 16.3 KB
/
service_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
package onet
import (
"bytes"
"errors"
"net/http"
"testing"
"time"
"sync"
"github.com/dedis/onet/log"
"github.com/dedis/onet/network"
"github.com/dedis/protobuf"
"github.com/stretchr/testify/require"
)
const dummyServiceName = "dummyService"
const dummyService2Name = "dummyService2"
const ismServiceName = "ismService"
const backForthServiceName = "backForth"
const dummyProtocolName = "DummyProtocol2"
func init() {
network.RegisterMessage(SimpleMessageForth{})
network.RegisterMessage(SimpleMessageBack{})
network.RegisterMessage(SimpleRequest{})
dummyMsgType = network.RegisterMessage(DummyMsg{})
RegisterNewService(ismServiceName, newServiceMessages)
RegisterNewService(dummyService2Name, newDummyService2)
GlobalProtocolRegister(dummyProtocolName, newDummyProtocol2)
}
func TestServiceRegistration(t *testing.T) {
var name = "dummy"
RegisterNewService(name, func(c *Context) (Service, error) {
return &DummyService{}, nil
})
names := ServiceFactory.RegisteredServiceNames()
var found bool
for _, n := range names {
if n == name {
found = true
}
}
if !found {
t.Fatal("Name not found !?")
}
ServiceFactory.Unregister(name)
names = ServiceFactory.RegisteredServiceNames()
for _, n := range names {
if n == name {
t.Fatal("Dummy should not be found!")
}
}
}
func TestServiceNew(t *testing.T) {
ds := &DummyService{
link: make(chan bool),
}
RegisterNewService(dummyServiceName, func(c *Context) (Service, error) {
ds.c = c
ds.link <- true
return ds, nil
})
defer UnregisterService(dummyServiceName)
go func() {
local := NewLocalTest(tSuite)
local.GenServers(1)
defer local.CloseAll()
}()
waitOrFatal(ds.link, t)
}
func TestServiceProcessRequest(t *testing.T) {
link := make(chan bool, 1)
_, err := RegisterNewService(dummyServiceName, func(c *Context) (Service, error) {
ds := &DummyService{
link: link,
c: c,
}
return ds, nil
})
log.ErrFatal(err)
defer UnregisterService(dummyServiceName)
local := NewTCPTest(tSuite)
hs := local.GenServers(2)
server := hs[0]
log.Lvl1("Host created and listening")
defer local.CloseAll()
// Send a request to the service
client := NewClient(tSuite, dummyServiceName)
log.Lvl1("Sending request to service...")
_, err = client.Send(server.ServerIdentity, "nil", []byte("a"))
log.Lvl2("Got reply")
require.Error(t, err)
// wait for the link
if <-link {
t.Fatal("was expecting false !")
}
}
// Test if a request that makes the service create a new protocol works
func TestServiceRequestNewProtocol(t *testing.T) {
ds := &DummyService{
link: make(chan bool, 1),
}
RegisterNewService(dummyServiceName, func(c *Context) (Service, error) {
ds.c = c
return ds, nil
})
defer UnregisterService(dummyServiceName)
local := NewTCPTest(tSuite)
hs := local.GenServers(2)
server := hs[0]
client := local.NewClient(dummyServiceName)
defer local.CloseAll()
// create the entityList and tree
el := NewRoster([]*network.ServerIdentity{server.ServerIdentity})
tree := el.GenerateBinaryTree()
// give it to the service
ds.fakeTree = tree
// Send a request to the service
log.Lvl1("Sending request to service...")
log.ErrFatal(client.SendProtobuf(server.ServerIdentity, &DummyMsg{10}, nil))
// wait for the link from the
waitOrFatalValue(ds.link, true, t)
// Now resend the value so we instantiate using the same treenode
log.Lvl1("Sending request again to service...")
err := client.SendProtobuf(server.ServerIdentity, &DummyMsg{10}, nil)
require.Error(t, err)
// this should fail
waitOrFatalValue(ds.link, false, t)
}
// test for calling the NewProtocol method on a remote Service
func TestServiceNewProtocol(t *testing.T) {
ds1 := &DummyService{
link: make(chan bool),
Config: DummyConfig{
Send: true,
},
}
ds2 := &DummyService{
link: make(chan bool),
}
var count int
countMutex := sync.Mutex{}
RegisterNewService(dummyServiceName, func(c *Context) (Service, error) {
countMutex.Lock()
defer countMutex.Unlock()
log.Lvl2("Creating service", count)
var localDs *DummyService
switch count {
case 2:
// the client does not need a Service
return &DummyService{link: make(chan bool)}, nil
case 1: // children
localDs = ds2
case 0: // root
localDs = ds1
}
localDs.c = c
count++
return localDs, nil
})
defer UnregisterService(dummyServiceName)
local := NewTCPTest(tSuite)
defer local.CloseAll()
hs := local.GenServers(3)
server1, server2 := hs[0], hs[1]
client := local.NewClient(dummyServiceName)
log.Lvl1("Host created and listening")
// create the entityList and tree
el := NewRoster([]*network.ServerIdentity{server1.ServerIdentity, server2.ServerIdentity})
tree := el.GenerateBinaryTree()
// give it to the service
ds1.fakeTree = tree
// Send a request to the service
log.Lvl1("Sending request to service...")
log.ErrFatal(client.SendProtobuf(server1.ServerIdentity, &DummyMsg{10}, nil))
log.Lvl1("Waiting for end")
// wait for the link from the protocol that Starts
waitOrFatalValue(ds1.link, true, t)
// now wait for the second link on the second HOST that the second service
// should have started (ds2) in ProcessRequest
waitOrFatalValue(ds2.link, true, t)
log.Lvl1("Done")
}
func TestServiceProcessor(t *testing.T) {
ds1 := &DummyService{
link: make(chan bool),
}
ds2 := &DummyService{
link: make(chan bool),
}
var count int
RegisterNewService(dummyServiceName, func(c *Context) (Service, error) {
var s *DummyService
if count == 0 {
s = ds1
} else {
s = ds2
}
s.c = c
c.RegisterProcessor(s, dummyMsgType)
return s, nil
})
local := NewLocalTest(tSuite)
defer local.CloseAll()
hs := local.GenServers(2)
server1, server2 := hs[0], hs[1]
defer UnregisterService(dummyServiceName)
// create two servers
log.Lvl1("Host created and listening")
// create request
log.Lvl1("Sending request to service...")
sentLen, err := server2.Send(server1.ServerIdentity, &DummyMsg{10})
require.Nil(t, err)
require.NotNil(t, sentLen)
// wait for the link from the Service on server 1
waitOrFatalValue(ds1.link, true, t)
}
func TestServiceBackForthProtocol(t *testing.T) {
local := NewTCPTest(tSuite)
defer local.CloseAll()
// register service
_, err := RegisterNewService(backForthServiceName, func(c *Context) (Service, error) {
return &simpleService{
ctx: c,
}, nil
})
log.ErrFatal(err)
defer ServiceFactory.Unregister(backForthServiceName)
// create servers
servers, el, _ := local.GenTree(4, false)
// create client
client := local.NewClient(backForthServiceName)
// create request
r := &SimpleRequest{
ServerIdentities: el,
Val: 10,
}
sr := &SimpleResponse{}
err = client.SendProtobuf(servers[0].ServerIdentity, r, sr)
log.ErrFatal(err)
require.Equal(t, sr.Val, 10)
}
func TestServiceManager_Service(t *testing.T) {
local := NewLocalTest(tSuite)
defer local.CloseAll()
servers, _, _ := local.GenTree(2, true)
services := servers[0].serviceManager.availableServices()
require.NotEqual(t, 0, len(services), "no services available")
service := servers[0].serviceManager.service("testService")
require.NotNil(t, service, "Didn't find service testService")
}
func TestServiceMessages(t *testing.T) {
local := NewLocalTest(tSuite)
defer local.CloseAll()
servers, _, _ := local.GenTree(2, true)
service := servers[0].serviceManager.service(ismServiceName)
require.NotNil(t, service, "Didn't find service ISMService")
ism := service.(*ServiceMessages)
ism.SendRaw(servers[0].ServerIdentity, &SimpleResponse{})
require.True(t, <-ism.GotResponse, "Didn't get response")
}
func TestServiceProtocolInstantiation(t *testing.T) {
local := NewLocalTest(tSuite)
defer local.CloseAll()
servers, _, tree := local.GenTree(2, true)
s1 := servers[0].serviceManager.service(dummyService2Name)
s2 := servers[1].serviceManager.service(dummyService2Name)
ds1 := s1.(*dummyService2)
ds2 := s2.(*dummyService2)
link := make(chan bool)
ds1.link = link
ds2.link = link
go ds1.launchProtoStart(tree, false, true)
waitOrFatal(link, t)
waitOrFatal(link, t)
waitOrFatal(link, t)
}
func TestServiceGenericConfig(t *testing.T) {
local := NewLocalTest(tSuite)
defer local.CloseAll()
servers, _, tree := local.GenTree(2, true)
s1 := servers[0].serviceManager.service(dummyService2Name)
s2 := servers[1].serviceManager.service(dummyService2Name)
ds1 := s1.(*dummyService2)
ds2 := s2.(*dummyService2)
link := make(chan bool)
ds1.link = link
ds2.link = link
// First launch without any config
go ds1.launchProto(tree, false)
// wait for the service's protocol creation
waitOrFatalValue(link, true, t)
// wait for the service 2 say there is no config
waitOrFatalValue(link, false, t)
// then laucnh with config
go ds1.launchProto(tree, true)
// wait for the service's protocol creation
waitOrFatalValue(link, true, t)
// wait for the service 2 say there is no config
waitOrFatalValue(link, true, t)
}
// BackForthProtocolForth & Back are messages that go down and up the tree.
// => BackForthProtocol protocol / message
type SimpleMessageForth struct {
Val int
}
type SimpleMessageBack struct {
Val int
}
type BackForthProtocol struct {
*TreeNodeInstance
Val int
counter int
forthChan chan struct {
*TreeNode
SimpleMessageForth
}
backChan chan struct {
*TreeNode
SimpleMessageBack
}
handler func(val int)
}
func newBackForthProtocolRoot(tn *TreeNodeInstance, val int, handler func(int)) (ProtocolInstance, error) {
s, err := newBackForthProtocol(tn)
s.Val = val
s.handler = handler
return s, err
}
func newBackForthProtocol(tn *TreeNodeInstance) (*BackForthProtocol, error) {
s := &BackForthProtocol{
TreeNodeInstance: tn,
}
err := s.RegisterChannel(&s.forthChan)
if err != nil {
return nil, err
}
err = s.RegisterChannel(&s.backChan)
if err != nil {
return nil, err
}
go s.dispatch()
return s, nil
}
func (sp *BackForthProtocol) Start() error {
// send down to children
msg := &SimpleMessageForth{
Val: sp.Val,
}
for _, ch := range sp.Children() {
if err := sp.SendTo(ch, msg); err != nil {
return err
}
}
return nil
}
func (sp *BackForthProtocol) dispatch() {
for {
select {
// dispatch the first msg down
case m := <-sp.forthChan:
msg := &m.SimpleMessageForth
for _, ch := range sp.Children() {
sp.SendTo(ch, msg)
}
if sp.IsLeaf() {
if err := sp.SendTo(sp.Parent(), &SimpleMessageBack{msg.Val}); err != nil {
log.Error(err)
}
sp.Done()
return
}
// pass the message up
case m := <-sp.backChan:
msg := m.SimpleMessageBack
// call the handler if we are the root
sp.counter++
if sp.counter == len(sp.Children()) {
if sp.IsRoot() {
sp.handler(msg.Val)
} else {
sp.SendTo(sp.Parent(), &msg)
}
sp.Done()
return
}
}
}
}
// Client API request / response emulation
type SimpleRequest struct {
ServerIdentities *Roster
Val int
}
type SimpleResponse struct {
Val int
}
var SimpleResponseType = network.RegisterMessage(SimpleResponse{})
type simpleService struct {
ctx *Context
}
func (s *simpleService) ProcessClientRequest(req *http.Request, path string, buf []byte) ([]byte, error) {
msg := &SimpleRequest{}
err := protobuf.DecodeWithConstructors(buf, msg, network.DefaultConstructors(tSuite))
if err != nil {
return nil, errors.New("")
}
tree := msg.ServerIdentities.GenerateBinaryTree()
tni := s.ctx.NewTreeNodeInstance(tree, tree.Root, backForthServiceName)
ret := make(chan int)
proto, err := newBackForthProtocolRoot(tni, msg.Val, func(n int) {
ret <- n
})
if err != nil {
return nil, errors.New("")
}
if err = s.ctx.RegisterProtocolInstance(proto); err != nil {
return nil, errors.New("")
}
proto.Start()
resp, err := protobuf.Encode(&SimpleResponse{<-ret})
if err != nil {
return nil, errors.New("")
}
return resp, nil
}
func (s *simpleService) NewProtocol(tni *TreeNodeInstance, conf *GenericConfig) (ProtocolInstance, error) {
pi, err := newBackForthProtocol(tni)
return pi, err
}
func (s *simpleService) Process(env *network.Envelope) {
return
}
type DummyProtocol struct {
*TreeNodeInstance
link chan bool
config DummyConfig
}
type DummyConfig struct {
A int
Send bool
}
type DummyMsg struct {
A int
}
var dummyMsgType network.MessageTypeID
func newDummyProtocol(tni *TreeNodeInstance, conf DummyConfig, link chan bool) *DummyProtocol {
return &DummyProtocol{tni, link, conf}
}
func (dm *DummyProtocol) Start() error {
dm.link <- true
if dm.config.Send {
// also send to the children if any
if !dm.IsLeaf() {
if err := dm.SendToChildren(&DummyMsg{}); err != nil {
log.Error(err)
}
}
}
return nil
}
func (dm *DummyProtocol) ProcessProtocolMsg(msg *ProtocolMsg) {
dm.link <- true
}
// legacy reasons
func (dm *DummyProtocol) Dispatch() error {
return nil
}
type DummyService struct {
c *Context
link chan bool
fakeTree *Tree
firstTni *TreeNodeInstance
Config DummyConfig
}
func (ds *DummyService) ProcessClientRequest(req *http.Request, path string, buf []byte) ([]byte, error) {
log.Lvl2("Got called with path", path, buf)
msg := &DummyMsg{}
err := protobuf.Decode(buf, msg)
if err != nil {
ds.link <- false
return nil, errors.New("wrong message")
}
if ds.firstTni == nil {
ds.firstTni = ds.c.NewTreeNodeInstance(ds.fakeTree, ds.fakeTree.Root, dummyServiceName)
}
dp := newDummyProtocol(ds.firstTni, ds.Config, ds.link)
if err := ds.c.RegisterProtocolInstance(dp); err != nil {
ds.link <- false
return nil, errors.New("")
}
log.Lvl2("Starting protocol")
go func() {
log.ErrFatal(dp.Start())
}()
return nil, nil
}
func (ds *DummyService) NewProtocol(tn *TreeNodeInstance, conf *GenericConfig) (ProtocolInstance, error) {
dp := newDummyProtocol(tn, DummyConfig{}, ds.link)
return dp, nil
}
func (ds *DummyService) Process(env *network.Envelope) {
if !env.MsgType.Equal(dummyMsgType) {
ds.link <- false
return
}
dms := env.Msg.(*DummyMsg)
if dms.A != 10 {
ds.link <- false
return
}
ds.link <- true
}
type ServiceMessages struct {
*ServiceProcessor
GotResponse chan bool
}
func (i *ServiceMessages) SimpleResponse(env *network.Envelope) {
i.GotResponse <- true
}
func newServiceMessages(c *Context) (Service, error) {
s := &ServiceMessages{
ServiceProcessor: NewServiceProcessor(c),
GotResponse: make(chan bool),
}
c.RegisterProcessorFunc(SimpleResponseType, s.SimpleResponse)
return s, nil
}
type dummyService2 struct {
*Context
link chan bool
}
func newDummyService2(c *Context) (Service, error) {
return &dummyService2{Context: c}, nil
}
func (ds *dummyService2) ProcessClientRequest(req *http.Request, path string, buf []byte) ([]byte, error) {
panic("should not be called")
}
var serviceConfig = []byte{0x01, 0x02, 0x03, 0x04}
func (ds *dummyService2) NewProtocol(tn *TreeNodeInstance, conf *GenericConfig) (ProtocolInstance, error) {
ds.link <- conf != nil && bytes.Equal(conf.Data, serviceConfig)
return newDummyProtocol2(tn)
}
func (ds *dummyService2) Process(env *network.Envelope) {
panic("should not be called")
}
func (ds *dummyService2) launchProto(t *Tree, config bool) {
ds.launchProtoStart(t, config, false)
}
func (ds *dummyService2) launchProtoStart(t *Tree, config, startNew bool) {
tni := ds.NewTreeNodeInstance(t, t.Root, dummyService2Name)
pi, err := newDummyProtocol2(tni)
pi.(*DummyProtocol2).startNewProtocol = startNew
err2 := ds.RegisterProtocolInstance(pi)
ds.link <- err == nil && err2 == nil
if config {
tni.SetConfig(&GenericConfig{serviceConfig})
}
go func() {
log.ErrFatal(pi.Start())
}()
}
type DummyProtocol2 struct {
*TreeNodeInstance
c chan WrapDummyMsg
startNewProtocol bool
}
type WrapDummyMsg struct {
*TreeNode
DummyMsg
}
func newDummyProtocol2(n *TreeNodeInstance) (ProtocolInstance, error) {
d := &DummyProtocol2{TreeNodeInstance: n}
d.c = make(chan WrapDummyMsg, 1)
d.RegisterChannel(d.c)
return d, nil
}
func (dp2 *DummyProtocol2) Start() error {
if dp2.startNewProtocol {
pi, err := dp2.CreateProtocol(dummyProtocolName, dp2.Tree())
if err != nil {
log.Error(err)
return err
}
go pi.Start()
}
return dp2.SendToChildren(&DummyMsg{20})
}
func waitOrFatalValue(ch chan bool, v bool, t *testing.T) {
select {
case b := <-ch:
if v != b {
t.Fatal("Wrong value returned on channel")
}
case <-time.After(500 * time.Millisecond):
t.Fatal("Waited too long")
}
}
func waitOrFatal(ch chan bool, t *testing.T) {
select {
case _ = <-ch:
return
case <-time.After(500 * time.Millisecond):
t.Fatal("Waited too long")
}
}