Skip to content

Commit 5bf5bed

Browse files
committed
Revert 7c8bfbd and add test
Don't block Close on spawned goroutines
1 parent f3f3750 commit 5bf5bed

File tree

4 files changed

+37
-148
lines changed

4 files changed

+37
-148
lines changed

datachannel.go

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ type DataChannel struct {
4040
readyState atomic.Value // DataChannelState
4141
bufferedAmountLowThreshold uint64
4242
detachCalled bool
43-
readLoopActive chan struct{}
4443

4544
// The binaryType represents attribute MUST, on getting, return the value to
4645
// which it was last set. On setting, if the new value is either the string
@@ -328,7 +327,6 @@ func (d *DataChannel) handleOpen(dc *datachannel.DataChannel, isRemote, isAlread
328327
defer d.mu.Unlock()
329328

330329
if !d.api.settingEngine.detach.DataChannels {
331-
d.readLoopActive = make(chan struct{})
332330
go d.readLoop()
333331
}
334332
}
@@ -358,7 +356,6 @@ var rlBufPool = sync.Pool{New: func() interface{} {
358356
}}
359357

360358
func (d *DataChannel) readLoop() {
361-
defer close(d.readLoopActive)
362359
for {
363360
buffer := rlBufPool.Get().([]byte) //nolint:forcetypeassert
364361
n, isString, err := d.dataChannel.ReadDataChannel(buffer)
@@ -441,22 +438,6 @@ func (d *DataChannel) Detach() (datachannel.ReadWriteCloser, error) {
441438
// Close Closes the DataChannel. It may be called regardless of whether
442439
// the DataChannel object was created by this peer or the remote peer.
443440
func (d *DataChannel) Close() error {
444-
return d.close(false)
445-
}
446-
447-
// Normally, close only stops writes from happening, so waitForReadsDone=true
448-
// will wait for reads to be finished based on underlying SCTP association
449-
// closure or a SCTP reset stream from the other side. This is safe to call
450-
// with waitForReadsDone=true after tearing down a PeerConnection but not
451-
// necessarily before. For example, if you used a vnet and dropped all packets
452-
// right before closing the DataChannel, you'd need never see a reset stream.
453-
func (d *DataChannel) close(waitForReadsDone bool) error {
454-
if waitForReadsDone && d.readLoopActive != nil {
455-
defer func() {
456-
<-d.readLoopActive
457-
}()
458-
}
459-
460441
d.mu.Lock()
461442
haveSctpTransport := d.dataChannel != nil
462443
d.mu.Unlock()

peerconnection.go

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ type PeerConnection struct {
5656
idpLoginURL *string
5757

5858
isClosed *atomicBool
59-
isClosedDone chan struct{}
6059
isNegotiationNeeded *atomicBool
6160
updateNegotiationNeededFlagOnEmptyChain *atomicBool
6261

@@ -128,7 +127,6 @@ func (api *API) NewPeerConnection(configuration Configuration) (*PeerConnection,
128127
ICECandidatePoolSize: 0,
129128
},
130129
isClosed: &atomicBool{},
131-
isClosedDone: make(chan struct{}),
132130
isNegotiationNeeded: &atomicBool{},
133131
updateNegotiationNeededFlagOnEmptyChain: &atomicBool{},
134132
lastOffer: "",
@@ -2036,31 +2034,14 @@ func (pc *PeerConnection) writeRTCP(pkts []rtcp.Packet, _ interceptor.Attributes
20362034
return pc.dtlsTransport.WriteRTCP(pkts)
20372035
}
20382036

2039-
// Close ends the PeerConnection.
2040-
// It will make a best effort to wait for all underlying goroutines it spawned to finish,
2041-
// except for cases that would cause deadlocks with itself.
2037+
// Close ends the PeerConnection
20422038
func (pc *PeerConnection) Close() error {
20432039
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #1)
20442040
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #2)
20452041
if pc.isClosed.swap(true) {
2046-
// someone else got here first but may still be closing (e.g. via DTLS close_notify)
2047-
<-pc.isClosedDone
20482042
return nil
20492043
}
2050-
defer close(pc.isClosedDone)
20512044

2052-
// Try closing everything and collect the errors
2053-
// Shutdown strategy:
2054-
// 1. Close all data channels.
2055-
// 2. All Conn close by closing their underlying Conn.
2056-
// 3. A Mux stops this chain. It won't close the underlying
2057-
// Conn if one of the endpoints is closed down. To
2058-
// continue the chain the Mux has to be closed.
2059-
pc.sctpTransport.lock.Lock()
2060-
closeErrs := make([]error, 0, 4+len(pc.sctpTransport.dataChannels))
2061-
pc.sctpTransport.lock.Unlock()
2062-
2063-
// canon steps
20642045
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3)
20652046
pc.signalingState.Set(SignalingStateClosed)
20662047

@@ -2070,6 +2051,7 @@ func (pc *PeerConnection) Close() error {
20702051
// 2. A Mux stops this chain. It won't close the underlying
20712052
// Conn if one of the endpoints is closed down. To
20722053
// continue the chain the Mux has to be closed.
2054+
closeErrs := make([]error, 4)
20732055

20742056
closeErrs = append(closeErrs, pc.api.interceptor.Close())
20752057

@@ -2096,6 +2078,7 @@ func (pc *PeerConnection) Close() error {
20962078

20972079
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #7)
20982080
closeErrs = append(closeErrs, pc.dtlsTransport.Stop())
2081+
20992082
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #8, #9, #10)
21002083
if pc.iceTransport != nil {
21012084
closeErrs = append(closeErrs, pc.iceTransport.Stop())
@@ -2104,13 +2087,6 @@ func (pc *PeerConnection) Close() error {
21042087
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #11)
21052088
pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State())
21062089

2107-
// non-canon steps
2108-
pc.sctpTransport.lock.Lock()
2109-
for _, d := range pc.sctpTransport.dataChannels {
2110-
closeErrs = append(closeErrs, d.close(true))
2111-
}
2112-
pc.sctpTransport.lock.Unlock()
2113-
21142090
return util.FlattenErrs(closeErrs)
21152091
}
21162092

peerconnection_close_test.go

Lines changed: 0 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
package webrtc
88

99
import (
10-
"runtime"
11-
"strings"
1210
"testing"
1311
"time"
1412

@@ -181,103 +179,3 @@ func TestPeerConnection_Close_DuringICE(t *testing.T) {
181179
t.Error("pcOffer.Close() Timeout")
182180
}
183181
}
184-
185-
func TestPeerConnection_CloseWithIncomingMessages(t *testing.T) {
186-
// Limit runtime in case of deadlocks
187-
lim := test.TimeOut(time.Second * 20)
188-
defer lim.Stop()
189-
190-
report := CheckRoutinesIntolerant(t)
191-
defer report()
192-
193-
pcOffer, pcAnswer, err := newPair()
194-
if err != nil {
195-
t.Fatal(err)
196-
}
197-
198-
var dcAnswer *DataChannel
199-
answerDataChannelOpened := make(chan struct{})
200-
pcAnswer.OnDataChannel(func(d *DataChannel) {
201-
// Make sure this is the data channel we were looking for. (Not the one
202-
// created in signalPair).
203-
if d.Label() != "data" {
204-
return
205-
}
206-
dcAnswer = d
207-
close(answerDataChannelOpened)
208-
})
209-
210-
dcOffer, err := pcOffer.CreateDataChannel("data", nil)
211-
if err != nil {
212-
t.Fatal(err)
213-
}
214-
215-
offerDataChannelOpened := make(chan struct{})
216-
dcOffer.OnOpen(func() {
217-
close(offerDataChannelOpened)
218-
})
219-
220-
err = signalPair(pcOffer, pcAnswer)
221-
if err != nil {
222-
t.Fatal(err)
223-
}
224-
225-
<-offerDataChannelOpened
226-
<-answerDataChannelOpened
227-
228-
msgNum := 0
229-
dcOffer.OnMessage(func(_ DataChannelMessage) {
230-
t.Log("msg", msgNum)
231-
msgNum++
232-
})
233-
234-
// send 50 messages, then close pcOffer, and then send another 50
235-
for i := 0; i < 100; i++ {
236-
if i == 50 {
237-
err = pcOffer.Close()
238-
if err != nil {
239-
t.Fatal(err)
240-
}
241-
}
242-
_ = dcAnswer.Send([]byte("hello!"))
243-
}
244-
245-
err = pcAnswer.Close()
246-
if err != nil {
247-
t.Fatal(err)
248-
}
249-
}
250-
251-
// CheckRoutinesIntolerant is used to check for leaked go-routines.
252-
// It differs from test.CheckRoutines in that it won't wait at all
253-
// for lingering goroutines. This is helpful for tests that need
254-
// to ensure clean closure of resources.
255-
func CheckRoutinesIntolerant(t *testing.T) func() {
256-
return func() {
257-
routines := getRoutines()
258-
if len(routines) == 0 {
259-
return
260-
}
261-
t.Fatalf("%s: \n%s", "Unexpected routines on test end", strings.Join(routines, "\n\n")) // nolint
262-
}
263-
}
264-
265-
func getRoutines() []string {
266-
buf := make([]byte, 2<<20)
267-
buf = buf[:runtime.Stack(buf, true)]
268-
return filterRoutines(strings.Split(string(buf), "\n\n"))
269-
}
270-
271-
func filterRoutines(routines []string) []string {
272-
result := []string{}
273-
for _, stack := range routines {
274-
if stack == "" || // Empty
275-
strings.Contains(stack, "testing.Main(") || // Tests
276-
strings.Contains(stack, "testing.(*T).Run(") || // Test run
277-
strings.Contains(stack, "getRoutines(") { // This routine
278-
continue
279-
}
280-
result = append(result, stack)
281-
}
282-
return result
283-
}

peerconnection_go_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1623,3 +1623,37 @@ func TestPeerConnectionState(t *testing.T) {
16231623
assert.NoError(t, pc.Close())
16241624
assert.Equal(t, PeerConnectionStateClosed, pc.ConnectionState())
16251625
}
1626+
1627+
func TestPeerConnectionDeadlock(t *testing.T) {
1628+
lim := test.TimeOut(time.Second * 5)
1629+
defer lim.Stop()
1630+
1631+
report := test.CheckRoutines(t)
1632+
defer report()
1633+
1634+
closeHdlr := func(peerConnection *PeerConnection) {
1635+
peerConnection.OnICEConnectionStateChange(func(i ICEConnectionState) {
1636+
if i == ICEConnectionStateFailed || i == ICEConnectionStateClosed {
1637+
if err := peerConnection.Close(); err != nil {
1638+
assert.NoError(t, err)
1639+
}
1640+
}
1641+
})
1642+
}
1643+
1644+
pcOffer, pcAnswer, err := NewAPI().newPair(Configuration{})
1645+
assert.NoError(t, err)
1646+
1647+
assert.NoError(t, signalPair(pcOffer, pcAnswer))
1648+
1649+
onDataChannel, onDataChannelCancel := context.WithCancel(context.Background())
1650+
pcAnswer.OnDataChannel(func(*DataChannel) {
1651+
onDataChannelCancel()
1652+
})
1653+
<-onDataChannel.Done()
1654+
1655+
closeHdlr(pcOffer)
1656+
closeHdlr(pcAnswer)
1657+
1658+
closePairNow(t, pcOffer, pcAnswer)
1659+
}

0 commit comments

Comments
 (0)