forked from livepeer/go-livepeer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorch_test.go
1749 lines (1477 loc) · 56.2 KB
/
orch_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
package core
import (
"database/sql"
"errors"
"fmt"
"io/ioutil"
"math"
"math/big"
"math/rand"
"os"
"strconv"
"sync"
"testing"
"time"
"github.com/golang/glog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/livepeer/go-livepeer/pm"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/livepeer/go-livepeer/common"
"github.com/livepeer/go-livepeer/drivers"
"github.com/livepeer/lpms/ffmpeg"
"github.com/livepeer/go-livepeer/net"
)
var defaultRecipient = ethcommon.BytesToAddress([]byte("defaultRecipient"))
func TestCurrentBlock(t *testing.T) {
tmpdir, _ := ioutil.TempDir("", "")
n, err := NewLivepeerNode(nil, tmpdir, nil)
if err != nil {
t.Error(err)
}
defer os.RemoveAll(tmpdir)
rm := &stubRoundsManager{}
orch := NewOrchestrator(n, rm)
// test empty db
if orch.CurrentBlock() != nil {
t.Error("Expected nil block")
}
db, dbraw, err := common.TempDB(t)
if err != nil {
t.Error("Error creating db ", err)
}
defer db.Close()
defer dbraw.Close()
n.Database = db
blkNum := big.NewInt(1234)
blkHash := ethcommon.BytesToHash([]byte("foo"))
if _, err := dbraw.Exec(fmt.Sprintf("INSERT INTO blockheaders(number, parent, hash, logs) VALUES(%v, \"\", %v, \"[]\")", blkNum.Int64(), blkHash.Hex())); err != nil {
t.Error("Unexpected error inserting mini header ", err)
}
if orch.CurrentBlock().Int64() != blkNum.Int64() {
t.Error("Unexpected block ", orch.CurrentBlock())
}
if _, err := dbraw.Exec(fmt.Sprintf("DELETE FROM blockheaders WHERE hash = %v", blkHash.Hex())); err != nil {
t.Error("Unexpected error deleting mini header ", err)
}
if orch.CurrentBlock() != nil {
t.Error("Expected nil getting nonexistent row")
}
}
func TestServeTranscoder(t *testing.T) {
n, _ := NewLivepeerNode(nil, "", nil)
n.TranscoderManager = NewRemoteTranscoderManager()
strm := &StubTranscoderServer{}
// test that a transcoder was created
go n.serveTranscoder(strm, 5)
time.Sleep(1 * time.Second)
tc, ok := n.TranscoderManager.liveTranscoders[strm]
if !ok {
t.Error("Unexpected transcoder type")
}
// test shutdown
tc.eof <- struct{}{}
time.Sleep(1 * time.Second)
// stream should be removed
_, ok = n.TranscoderManager.liveTranscoders[strm]
if ok {
t.Error("Unexpected transcoder presence")
}
}
func TestRemoteTranscoder(t *testing.T) {
m := NewRemoteTranscoderManager()
initTranscoder := func() (*RemoteTranscoder, *StubTranscoderServer) {
strm := &StubTranscoderServer{manager: m}
tc := NewRemoteTranscoder(m, strm, 5)
return tc, strm
}
// happy path
tc, strm := initTranscoder()
res, err := tc.Transcode(&SegTranscodingMetadata{})
if err != nil || string(res.Segments[0].Data) != "asdf" {
t.Error("Error transcoding ", err)
}
// error on remote while transcoding
tc, strm = initTranscoder()
strm.TranscodeError = fmt.Errorf("TranscodeError")
res, err = tc.Transcode(&SegTranscodingMetadata{})
if err != strm.TranscodeError {
t.Error("Unexpected error ", err, res)
}
// simulate error with sending
tc, strm = initTranscoder()
strm.SendError = fmt.Errorf("SendError")
_, err = tc.Transcode(&SegTranscodingMetadata{})
if _, fatal := err.(RemoteTranscoderFatalError); !fatal ||
err.Error() != strm.SendError.Error() {
t.Error("Unexpected error ", err, fatal)
}
assert := assert.New(t)
// check default timeout
tc, strm = initTranscoder()
strm.WithholdResults = true
m.taskCount = 1001
oldTimeout := common.HTTPTimeout
defer func() { common.HTTPTimeout = oldTimeout }()
common.HTTPTimeout = 5 * time.Millisecond
// count relative ticks rather than wall clock to mitigate CI slowness
countTicks := func(exitVal chan int, stopper chan struct{}) {
ticker := time.NewTicker(time.Millisecond)
ticks := 0
for {
select {
case <-stopper:
exitVal <- ticks
return
case <-ticker.C:
ticks++
}
}
}
tickCh := make(chan int, 1)
stopper := make(chan struct{})
go countTicks(tickCh, stopper)
var wg sync.WaitGroup
wg.Add(1)
go func() {
_, err = tc.Transcode(&SegTranscodingMetadata{ManifestID: ManifestID("fileName")})
assert.Equal("Remote transcoder took too long", err.Error())
wg.Done()
}()
assert.True(wgWait(&wg), "transcoder took too long to timeout")
stopper <- struct{}{}
ticksWhenSegIsShort := <-tickCh
// check timeout based on segment duration
tc, strm = initTranscoder()
strm.WithholdResults = true
m.taskCount = 1002
assert.Equal(5*time.Millisecond, common.HTTPTimeout) // sanity check
tickCh = make(chan int, 1)
stopper = make(chan struct{}, 1)
go countTicks(tickCh, stopper)
wg.Add(1)
go func() {
dur := 25 * time.Millisecond
_, err = tc.Transcode(&SegTranscodingMetadata{Duration: dur})
assert.Equal("Remote transcoder took too long", err.Error())
wg.Done()
}()
assert.True(wgWait(&wg), "transcoder took too long to timeout")
stopper <- struct{}{}
ticksWhenSegIsLong := <-tickCh
// attempt to ensure that we didn't trigger the default timeout
assert.Greater(ticksWhenSegIsLong, ticksWhenSegIsShort*2, "not enough of a difference between default and long timeouts")
// sanity check that ticksWhenSegIsShort is also a reasonable value
assert.Greater(ticksWhenSegIsShort*25, ticksWhenSegIsLong)
}
func newWg(delta int) *sync.WaitGroup {
var wg sync.WaitGroup
wg.Add(delta)
return &wg
}
func wgWait(wg *sync.WaitGroup) bool {
c := make(chan struct{})
go func() { defer close(c); wg.Wait() }()
select {
case <-c:
return true
case <-time.After(1 * time.Second):
return false
}
}
func wgWait2(wg *sync.WaitGroup, dur time.Duration) bool {
c := make(chan struct{})
go func() { defer close(c); wg.Wait() }()
select {
case <-c:
return true
case <-time.After(dur):
return false
}
}
func TestManageTranscoders(t *testing.T) {
m := NewRemoteTranscoderManager()
strm := &StubTranscoderServer{}
strm2 := &StubTranscoderServer{manager: m}
// sanity check that liveTranscoders and remoteTranscoders is empty
assert := assert.New(t)
assert.Nil(m.liveTranscoders[strm])
assert.Nil(m.liveTranscoders[strm2])
assert.Empty(m.remoteTranscoders)
assert.Equal(0, m.RegisteredTranscodersCount())
// test that transcoder is added to liveTranscoders and remoteTranscoders
wg1 := newWg(1)
go func() { m.Manage(strm, 5); wg1.Done() }()
time.Sleep(1 * time.Millisecond) // allow the manager to activate
assert.NotNil(m.liveTranscoders[strm])
assert.Len(m.liveTranscoders, 1)
assert.Len(m.remoteTranscoders, 1)
assert.Equal(1, m.RegisteredTranscodersCount())
ti := m.RegisteredTranscodersInfo()
assert.Len(ti, 1)
assert.Equal(5, ti[0].Capacity)
assert.Equal("TestAddress", ti[0].Address)
// test that additional transcoder is added to liveTranscoders and remoteTranscoders
wg2 := newWg(1)
go func() { m.Manage(strm2, 4); wg2.Done() }()
time.Sleep(1 * time.Millisecond) // allow the manager to activate
assert.NotNil(m.liveTranscoders[strm])
assert.NotNil(m.liveTranscoders[strm2])
assert.Len(m.liveTranscoders, 2)
assert.Len(m.remoteTranscoders, 2)
assert.Equal(2, m.RegisteredTranscodersCount())
// test that transcoders are removed from liveTranscoders and remoteTranscoders
m.liveTranscoders[strm].eof <- struct{}{}
assert.True(wgWait(wg1)) // time limit
assert.Nil(m.liveTranscoders[strm])
assert.NotNil(m.liveTranscoders[strm2])
assert.Len(m.liveTranscoders, 1)
assert.Len(m.remoteTranscoders, 2)
assert.Equal(1, m.RegisteredTranscodersCount())
m.liveTranscoders[strm2].eof <- struct{}{}
assert.True(wgWait(wg2)) // time limit
assert.Nil(m.liveTranscoders[strm])
assert.Nil(m.liveTranscoders[strm2])
assert.Len(m.liveTranscoders, 0)
assert.Len(m.remoteTranscoders, 2)
assert.Equal(0, m.RegisteredTranscodersCount())
}
func TestSelectTranscoder(t *testing.T) {
m := NewRemoteTranscoderManager()
strm := &StubTranscoderServer{manager: m, WithholdResults: false}
strm2 := &StubTranscoderServer{manager: m}
// sanity check that transcoder is not in liveTranscoders or remoteTranscoders
assert := assert.New(t)
assert.Nil(m.liveTranscoders[strm])
assert.Empty(m.remoteTranscoders)
// register transcoders, which adds transcoder to liveTranscoders and remoteTranscoders
wg := newWg(1)
go func() { m.Manage(strm, 1) }()
time.Sleep(1 * time.Millisecond) // allow time for first stream to register
go func() { m.Manage(strm2, 1); wg.Done() }()
time.Sleep(1 * time.Millisecond) // allow time for second stream to register
assert.NotNil(m.liveTranscoders[strm])
assert.NotNil(m.liveTranscoders[strm2])
assert.Len(m.remoteTranscoders, 2)
testSessionId := "testID"
testSessionId2 := "testID2"
testSessionId3 := "testID3"
// assert transcoder is returned from selectTranscoder
t1 := m.liveTranscoders[strm]
t2 := m.liveTranscoders[strm2]
currentTranscoder, err := m.selectTranscoder(testSessionId)
assert.Nil(err)
assert.Equal(t2, currentTranscoder)
assert.Equal(1, t2.load)
assert.NotNil(m.liveTranscoders[strm])
assert.Len(m.remoteTranscoders, 2)
// assert that same transcoder is selected for same sessionId
// and that load stays the same
currentTranscoder, err = m.selectTranscoder(testSessionId)
assert.Nil(err)
assert.Equal(t2, currentTranscoder)
assert.Equal(1, t2.load)
m.completeStreamSession(testSessionId)
// assert that a new transcoder is selected for a new sessionId
currentTranscoder, err = m.selectTranscoder(testSessionId2)
assert.Nil(err)
assert.Equal(t1, currentTranscoder)
assert.Equal(1, t1.load)
// Add some more load and assert no transcoder returned if all at capacity
currentTranscoder, err = m.selectTranscoder(testSessionId)
assert.Nil(err)
assert.Equal(t2, currentTranscoder)
noTrans, err := m.selectTranscoder(testSessionId3)
assert.Equal(err, ErrNoTranscodersAvailable)
assert.Nil(noTrans)
// assert that load is empty after ending stream sessions
m.completeStreamSession(testSessionId2)
assert.Equal(0, t1.load)
// unregister transcoder
t2.eof <- struct{}{}
assert.True(wgWait(wg), "Wait timed out for transcoder to terminate")
assert.Nil(m.liveTranscoders[strm2])
assert.NotNil(m.liveTranscoders[strm])
// assert t1 is selected and t2 drained, but was previously selected
currentTranscoder, err = m.selectTranscoder(testSessionId)
assert.Nil(err)
assert.Equal(t1, currentTranscoder)
assert.Equal(1, t1.load)
assert.NotNil(m.liveTranscoders[strm])
assert.Len(m.remoteTranscoders, 1)
// assert transcoder gets added back to remoteTranscoders if no transcoding error
transcodedData, err := m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}})
assert.NotNil(transcodedData)
assert.Nil(err)
assert.Len(m.remoteTranscoders, 1)
assert.Equal(1, t1.load)
m.completeStreamSession(testSessionId)
assert.Equal(0, t1.load)
}
func TestCompleteStreamSession(t *testing.T) {
m := NewRemoteTranscoderManager()
strm := &StubTranscoderServer{manager: m}
testSessionId := "testID"
assert := assert.New(t)
// register transcoders
go func() { m.Manage(strm, 1) }()
time.Sleep(1 * time.Millisecond) // allow time for first stream to register
t1 := m.liveTranscoders[strm]
// selectTranscoder and assert that session is added
m.selectTranscoder(testSessionId)
assert.Equal(t1, m.streamSessions[testSessionId])
assert.Equal(1, t1.load)
// complete session and assert that it is cleared
m.completeStreamSession(testSessionId)
transcoder, ok := m.streamSessions[testSessionId]
assert.Nil(transcoder)
assert.False(ok)
assert.Equal(0, t1.load)
}
func TestRemoveFromRemoteTranscoders(t *testing.T) {
remoteTranscoderList := []*RemoteTranscoder{}
assert := assert.New(t)
// Create 4 tanscoders
tr := make([]*RemoteTranscoder, 4)
for i := 0; i < 4; i++ {
tr[i] = &RemoteTranscoder{addr: "testAddress" + strconv.Itoa(i)}
}
// Add to list
remoteTranscoderList = append(remoteTranscoderList, tr...)
assert.Len(remoteTranscoderList, 4)
// Remove transcoder froms head of the list
remoteTranscoderList = removeFromRemoteTranscoders(tr[0], remoteTranscoderList)
assert.Equal(remoteTranscoderList[0], tr[1])
assert.Equal(remoteTranscoderList[1], tr[2])
assert.Equal(remoteTranscoderList[2], tr[3])
assert.Len(remoteTranscoderList, 3)
// Remove transcoder from the middle of the list
remoteTranscoderList = removeFromRemoteTranscoders(tr[3], remoteTranscoderList)
assert.Equal(remoteTranscoderList[0], tr[1])
assert.Equal(remoteTranscoderList[1], tr[2])
assert.Len(remoteTranscoderList, 2)
// Remove transcoder from the end of the list
remoteTranscoderList = removeFromRemoteTranscoders(tr[2], remoteTranscoderList)
assert.Equal(remoteTranscoderList[0], tr[1])
assert.Len(remoteTranscoderList, 1)
// Remove the last transcoder
remoteTranscoderList = removeFromRemoteTranscoders(tr[1], remoteTranscoderList)
assert.Len(remoteTranscoderList, 0)
// Remove a transcoder when list is empty
remoteTranscoderList = removeFromRemoteTranscoders(tr[1], remoteTranscoderList)
emptyTList := []*RemoteTranscoder{}
assert.Equal(remoteTranscoderList, emptyTList)
}
func TestTranscoderManagerTranscoding(t *testing.T) {
m := NewRemoteTranscoderManager()
s := &StubTranscoderServer{manager: m}
testSessionId := "testID"
// sanity checks
assert := assert.New(t)
assert.Empty(m.liveTranscoders)
assert.Empty(m.remoteTranscoders)
// Attempt to transcode when no transcoders in the set
transcodedData, err := m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}})
assert.Nil(transcodedData)
assert.NotNil(err)
assert.Equal(err, ErrNoTranscodersAvailable)
wg := newWg(1)
go func() { m.Manage(s, 5); wg.Done() }()
time.Sleep(1 * time.Millisecond)
assert.Len(m.remoteTranscoders, 1) // sanity
assert.Len(m.liveTranscoders, 1)
assert.NotNil(m.liveTranscoders[s])
// happy path
res, err := m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}})
assert.Nil(err)
assert.Len(res.Segments, 1)
assert.Equal(string(res.Segments[0].Data), "asdf")
// non-fatal error should not remove from list
s.TranscodeError = fmt.Errorf("TranscodeError")
transcodedData, err = m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}})
assert.NotNil(transcodedData)
assert.Equal(s.TranscodeError, err)
assert.Len(m.remoteTranscoders, 1) // sanity
assert.Equal(0, m.remoteTranscoders[0].load) // sanity
assert.Len(m.liveTranscoders, 1)
assert.NotNil(m.liveTranscoders[s])
s.TranscodeError = nil
// fatal error should retry and remove from list
s.SendError = fmt.Errorf("SendError")
transcodedData, err = m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}})
assert.True(wgWait(wg)) // should disconnect manager
assert.Nil(transcodedData)
assert.NotNil(err)
assert.Equal(err, ErrNoTranscodersAvailable)
transcodedData, err = m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}}) // need second try to remove from remoteTranscoders
assert.Nil(transcodedData)
assert.NotNil(err)
assert.Equal(err, ErrNoTranscodersAvailable)
assert.Len(m.liveTranscoders, 0)
assert.Len(m.remoteTranscoders, 0) // retries drain the list
s.SendError = nil
// fatal error should not retry
wg.Add(1)
go func() { m.Manage(s, 5); wg.Done() }()
time.Sleep(1 * time.Millisecond)
assert.Len(m.remoteTranscoders, 1) // sanity check
assert.Len(m.liveTranscoders, 1)
s.WithholdResults = true
oldTimeout := common.HTTPTimeout
common.HTTPTimeout = 1 * time.Millisecond
defer func() { common.HTTPTimeout = oldTimeout }()
transcodedData, err = m.Transcode(&SegTranscodingMetadata{AuthToken: &net.AuthToken{SessionId: testSessionId}})
assert.Nil(transcodedData)
_, fatal := err.(RemoteTranscoderFatalError)
wg.Wait()
assert.True(fatal)
assert.Len(m.liveTranscoders, 0)
assert.Len(m.remoteTranscoders, 1) // no retries, so don't drain
s.WithholdResults = false
}
func TestTaskChan(t *testing.T) {
n := NewRemoteTranscoderManager()
// Sanity check task ID
if n.taskCount != 0 {
t.Error("Unexpected taskid")
}
if len(n.taskChans) != int(n.taskCount) {
t.Error("Unexpected task chan length")
}
// Adding task chans
const MaxTasks = 1000
for i := 0; i < MaxTasks; i++ {
go n.addTaskChan() // hopefully concurrently...
}
for j := 0; j < 10; j++ {
n.taskMutex.RLock()
tid := n.taskCount
n.taskMutex.RUnlock()
if tid >= MaxTasks {
break
}
time.Sleep(10 * time.Millisecond)
}
if n.taskCount != MaxTasks {
t.Error("Time elapsed")
}
if len(n.taskChans) != int(n.taskCount) {
t.Error("Unexpected task chan length")
}
// Accessing task chans
existingIds := []int64{0, 1, MaxTasks / 2, MaxTasks - 2, MaxTasks - 1}
for _, id := range existingIds {
_, err := n.getTaskChan(int64(id))
if err != nil {
t.Error("Unexpected error getting task chan for ", id, err)
}
}
missingIds := []int64{-1, MaxTasks}
testNonexistentChans := func(ids []int64) {
for _, id := range ids {
_, err := n.getTaskChan(int64(id))
if err == nil || err.Error() != "No transcoder channel" {
t.Error("Did not get expected error for ", id, err)
}
}
}
testNonexistentChans(missingIds)
// Removing task chans
for i := 0; i < MaxTasks; i++ {
go n.removeTaskChan(int64(i)) // hopefully concurrently...
}
for j := 0; j < 10; j++ {
n.taskMutex.RLock()
tlen := len(n.taskChans)
n.taskMutex.RUnlock()
if tlen <= 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
if len(n.taskChans) != 0 {
t.Error("Time elapsed")
}
testNonexistentChans(existingIds) // sanity check for removal
}
type StubTranscoderServer struct {
manager *RemoteTranscoderManager
SendError error
TranscodeError error
WithholdResults bool
common.StubServerStream
}
func (s *StubTranscoderServer) Send(n *net.NotifySegment) error {
res := RemoteTranscoderResult{
TranscodeData: &TranscodeData{
Segments: []*TranscodedSegmentData{
{Data: []byte("asdf")},
},
},
Err: s.TranscodeError,
}
if !s.WithholdResults {
s.manager.transcoderResults(n.TaskId, &res)
}
return s.SendError
}
func StubSegTranscodingMetadata() *SegTranscodingMetadata {
return &SegTranscodingMetadata{
ManifestID: ManifestID("abcdef"),
Seq: 1234,
Hash: ethcommon.BytesToHash(ethcommon.RightPadBytes([]byte("browns"), 32)),
Profiles: []ffmpeg.VideoProfile{ffmpeg.P144p30fps16x9, ffmpeg.P240p30fps16x9},
OS: &net.OSInfo{StorageType: net.OSInfo_DIRECT},
AuthToken: stubAuthToken(),
}
}
func TestGetSegmentChan(t *testing.T) {
n, _ := NewLivepeerNode(nil, "", nil)
segData := StubSegTranscodingMetadata()
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
sc, err := n.getSegmentChan(segData)
if err != nil {
t.Error("error with getSegmentChan", err)
}
if sc != n.SegmentChans[ManifestID(segData.AuthToken.SessionId)] {
t.Error("SegmentChans mapping did not include channel")
}
if cap(sc) != maxSegmentChannels {
t.Error("returned segment channel is not the correct capacity")
}
// Test max sessions
oldTranscodeSessions := MaxSessions
MaxSessions = 0
if _, err := n.getSegmentChan(segData); err != nil {
t.Error("Existing mid should continue processing even when O is at capacity: ", err)
}
segData.AuthToken = stubAuthToken()
segData.AuthToken.SessionId = t.Name()
if _, err := n.getSegmentChan(segData); err != ErrOrchCap {
t.Error("Didn't fail when orch cap hit: ", err)
}
MaxSessions = oldTranscodeSessions
// Test what happens when invoking the transcode loop fails
drivers.NodeStorage = nil // will make the transcode loop fail
node, _ := NewLivepeerNode(nil, "", nil)
sc, storageError := node.getSegmentChan(segData)
if storageError.Error() != "Missing local storage" {
t.Error("transcodingLoop did not fail when expected to", storageError)
}
if _, ok := node.SegmentChans[segData.ManifestID]; ok {
t.Error("SegmentChans mapping included new channel when expected to return an err/nil")
}
// The following tests may seem identical to the two cases above
// however, calling `getSegmentChan` used to hang on the invocation after an
// error. Reproducing the scenario here but should not hang.
sc, storageErr := node.getSegmentChan(segData)
if storageErr.Error() != "Missing local storage" {
t.Error("transcodingLoop did not fail when expected to", storageErr)
}
if _, ok := node.SegmentChans[segData.ManifestID]; ok {
t.Error("SegmentChans mapping included new channel when expected to return an err/nil")
}
}
func TestOrchCheckCapacity(t *testing.T) {
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
n, _ := NewLivepeerNode(nil, "", nil)
o := NewOrchestrator(n, nil)
md := StubSegTranscodingMetadata()
cap := MaxSessions
assert := assert.New(t)
mid := ManifestID(md.AuthToken.SessionId)
// happy case
assert.Nil(o.CheckCapacity(mid))
// capped case
MaxSessions = 0
assert.Equal(ErrOrchCap, o.CheckCapacity(mid))
// ensure existing segment chans pass while cap is active
MaxSessions = cap
_, err := n.getSegmentChan(md) // store md into segment chans
assert.Nil(err)
MaxSessions = 0
assert.Nil(o.CheckCapacity(mid))
}
func TestProcessPayment_GivenRecipientError_ReturnsNil(t *testing.T) {
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Balances = NewAddressBalances(5 * time.Second)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
orch.node.SetBasePrice(big.NewRat(0, 1))
recipient.On("TxCostMultiplier", mock.Anything).Return(big.NewRat(1, 1), nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return("", false, nil)
err := orch.ProcessPayment(defaultPayment(t), ManifestID("some manifest"))
assert := assert.New(t)
assert.Nil(err)
}
func TestProcessPayment_GivenNoSender_ReturnsError(t *testing.T) {
n, _ := NewLivepeerNode(nil, "", nil)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
orch := NewOrchestrator(n, nil)
protoPayment := defaultPayment(t)
protoPayment.Sender = nil
err := orch.ProcessPayment(protoPayment, ManifestID("some manifest"))
assert := assert.New(t)
assert.Error(err)
}
func TestProcessPayment_GivenNoTicketParams_ReturnsNil(t *testing.T) {
n, _ := NewLivepeerNode(nil, "", nil)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
orch := NewOrchestrator(n, nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return("some sessionID", false, nil)
protoPayment := defaultPayment(t)
protoPayment.TicketParams = nil
err := orch.ProcessPayment(protoPayment, ManifestID("some manifest"))
assert := assert.New(t)
assert.Nil(err)
}
func TestProcessPayment_GivenNilNode_ReturnsNil(t *testing.T) {
orch := &orchestrator{}
err := orch.ProcessPayment(defaultPayment(t), ManifestID("some manifest"))
assert.Nil(t, err)
}
func TestProcessPayment_GivenNilRecipient_ReturnsNil(t *testing.T) {
n, _ := NewLivepeerNode(nil, "", nil)
orch := NewOrchestrator(n, nil)
n.Recipient = nil
err := orch.ProcessPayment(defaultPayment(t), ManifestID("some manifest"))
assert.Nil(t, err)
}
func TestProcessPayment_ActiveOrchestrator(t *testing.T) {
assert := assert.New(t)
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 1,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Balances = NewAddressBalances(5 * time.Second)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
orch.node.SetBasePrice(big.NewRat(0, 1))
// orchestrator inactive -> error
err := orch.ProcessPayment(defaultPayment(t), ManifestID("some manifest"))
expErr := fmt.Sprintf("orchestrator is inactive, cannot process payments")
assert.EqualError(err, expErr)
// orchestrator is active -> no error
dbh.UpdateOrch(&common.DBOrch{
EthereumAddr: orch.Address().Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
recipient.On("TxCostMultiplier", mock.Anything).Return(big.NewRat(1, 1), nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return("some sessionID", false, nil)
err = orch.ProcessPayment(defaultPayment(t), ManifestID("some manifest"))
assert.NoError(err)
}
func TestProcessPayment_InvalidExpectedPrice(t *testing.T) {
assert := assert.New(t)
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Recipient = new(pm.MockRecipient)
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
pay := defaultPayment(t)
// test ExpectedPrice.PixelsPerUnit = 0
pay.ExpectedPrice = &net.PriceInfo{PricePerUnit: 500, PixelsPerUnit: 0}
err := orch.ProcessPayment(pay, ManifestID("some manifest"))
assert.Error(err)
assert.EqualError(err, fmt.Sprintf("invalid expected price sent with payment err=%v", "pixels per unit is 0"))
// test ExpectedPrice = nil
pay.ExpectedPrice = nil
err = orch.ProcessPayment(pay, ManifestID("some manifest"))
assert.Error(err)
assert.EqualError(err, fmt.Sprintf("invalid expected price sent with payment err=%v", "expected price is nil"))
}
func TestProcessPayment_GivenLosingTicket_DoesNotRedeem(t *testing.T) {
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Balances = NewAddressBalances(5 * time.Second)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
orch.node.SetBasePrice(big.NewRat(0, 1))
recipient.On("TxCostMultiplier", mock.Anything).Return(big.NewRat(1, 1), nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return("some sessionID", false, nil)
err := orch.ProcessPayment(defaultPayment(t), ManifestID("some manifest"))
time.Sleep(time.Millisecond * 20)
assert := assert.New(t)
assert.Nil(err)
recipient.AssertNotCalled(t, "RedeemWinningTicket", mock.Anything, mock.Anything, mock.Anything)
}
func TestProcessPayment_GivenWinningTicket_RedeemError(t *testing.T) {
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Balances = NewAddressBalances(5 * time.Second)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
orch.node.SetBasePrice(big.NewRat(0, 1))
manifestID := ManifestID("some manifest")
sessionID := "some sessionID"
recipient.On("TxCostMultiplier", mock.Anything).Return(big.NewRat(1, 1), nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return(sessionID, true, nil)
recipient.On("RedeemWinningTicket", mock.Anything, mock.Anything, mock.Anything).Return(errors.New("RedeemWinningTicket error"))
errorLogsBefore := glog.Stats.Error.Lines()
err := orch.ProcessPayment(defaultPayment(t), manifestID)
time.Sleep(time.Millisecond * 20)
errorLogsAfter := glog.Stats.Error.Lines()
assert := assert.New(t)
assert.Nil(err)
assert.Equal(int64(1), errorLogsAfter-errorLogsBefore)
recipient.AssertCalled(t, "RedeemWinningTicket", mock.Anything, mock.Anything, mock.Anything)
}
func TestProcessPayment_GivenWinningTicket_Redeems(t *testing.T) {
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Balances = NewAddressBalances(5 * time.Second)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
orch.node.SetBasePrice(big.NewRat(0, 1))
manifestID := ManifestID("some manifest")
sessionID := "some sessionID"
recipient.On("TxCostMultiplier", mock.Anything).Return(big.NewRat(1, 1), nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return(sessionID, true, nil)
recipient.On("RedeemWinningTicket", mock.Anything, mock.Anything, mock.Anything).Return(nil)
errorLogsBefore := glog.Stats.Error.Lines()
err := orch.ProcessPayment(defaultPayment(t), manifestID)
time.Sleep(time.Millisecond * 20)
errorLogsAfter := glog.Stats.Error.Lines()
assert := assert.New(t)
assert.Zero(errorLogsAfter - errorLogsBefore)
assert.Nil(err)
recipient.AssertCalled(t, "RedeemWinningTicket", mock.Anything, mock.Anything, mock.Anything)
}
func TestProcessPayment_GivenMultipleWinningTickets_RedeemsAll(t *testing.T) {
addr := defaultRecipient
dbh, dbraw := tempDBWithOrch(t, &common.DBOrch{
EthereumAddr: addr.Hex(),
ActivationRound: 1,
DeactivationRound: 999,
})
defer dbh.Close()
defer dbraw.Close()
n, _ := NewLivepeerNode(nil, "", dbh)
n.Balances = NewAddressBalances(5 * time.Second)
recipient := new(pm.MockRecipient)
n.Recipient = recipient
rm := &stubRoundsManager{
round: big.NewInt(10),
}
orch := NewOrchestrator(n, rm)
orch.address = addr
orch.node.SetBasePrice(big.NewRat(0, 1))
manifestID := ManifestID("some manifest")
sessionID := "some sessionID"
recipient.On("TxCostMultiplier", mock.Anything).Return(big.NewRat(1, 1), nil)
recipient.On("ReceiveTicket", mock.Anything, mock.Anything, mock.Anything).Return(sessionID, true, nil)
numTickets := 5
recipient.On("RedeemWinningTicket", mock.Anything, mock.Anything, mock.Anything).Return(nil).Times(numTickets)
var senderParams []*net.TicketSenderParams
for i := 0; i < numTickets; i++ {
senderParams = append(
senderParams,
&net.TicketSenderParams{SenderNonce: 456 + uint32(i), Sig: pm.RandBytes(123)},
)
}
payment := *defaultPaymentWithTickets(t, senderParams)
ticketParams := &pm.TicketParams{
Recipient: ethcommon.BytesToAddress(payment.TicketParams.Recipient),