Locking/Ping cleanup

This commit is contained in:
Jakob Borg 2013-12-24 11:45:16 -05:00
parent 064bfd366f
commit fc4b23fbc6
4 changed files with 56 additions and 55 deletions

View File

@ -282,11 +282,6 @@ func connect(myID string, addr string, nodeAddrs map[string][]string, m *Model,
nc := protocol.NewConnection(nodeID, conn, conn, m) nc := protocol.NewConnection(nodeID, conn, conn, m)
okln("Connected to node", remoteID, "(out)") okln("Connected to node", remoteID, "(out)")
m.AddNode(nc) m.AddNode(nc)
if opts.Debug.TraceNet {
t0 := time.Now()
nc.Ping()
timing("NET: Ping reply", t0)
}
continue nextNode continue nextNode
} }
} }

View File

@ -60,7 +60,7 @@ func (m *Model) Start() {
func (m *Model) printStats() { func (m *Model) printStats() {
for { for {
time.Sleep(15 * time.Second) time.Sleep(60 * time.Second)
m.RLock() m.RLock()
for node, conn := range m.nodes { for node, conn := range m.nodes {
stats := conn.Statistics() stats := conn.Statistics()
@ -223,7 +223,7 @@ func (m *Model) ReplaceLocal(fs []File) {
m.recomputeGlobal() m.recomputeGlobal()
m.recomputeNeed() m.recomputeNeed()
m.updated = time.Now().Unix() m.updated = time.Now().Unix()
go m.broadcastIndex() m.broadcastIndex()
} }
} }
@ -231,10 +231,11 @@ func (m *Model) ReplaceLocal(fs []File) {
func (m *Model) broadcastIndex() { func (m *Model) broadcastIndex() {
idx := m.protocolIndex() idx := m.protocolIndex()
for _, node := range m.nodes { for _, node := range m.nodes {
node := node
if opts.Debug.TraceNet { if opts.Debug.TraceNet {
debugf("NET IDX(out): %s: %d files", node.ID, len(idx)) debugf("NET IDX(out): %s: %d files", node.ID, len(idx))
} }
node.Index(idx) go node.Index(idx)
} }
} }
@ -271,7 +272,7 @@ func (m *Model) UpdateLocal(f File) {
m.recomputeGlobal() m.recomputeGlobal()
m.recomputeNeed() m.recomputeNeed()
m.updated = time.Now().Unix() m.updated = time.Now().Unix()
go m.broadcastIndex() m.broadcastIndex()
} }
} }
@ -400,5 +401,8 @@ func (m *Model) AddNode(node *protocol.Connection) {
if opts.Debug.TraceNet { if opts.Debug.TraceNet {
debugf("NET IDX(out): %s: %d files", node.ID, len(idx)) debugf("NET IDX(out): %s: %d files", node.ID, len(idx))
} }
node.Index(idx)
// Sending the index might take a while if we have many files and a slow
// uplink. Return from AddNode in the meantime.
go node.Index(idx)
} }

View File

@ -42,13 +42,13 @@ type Model interface {
} }
type Connection struct { type Connection struct {
sync.RWMutex
ID string ID string
receiver Model receiver Model
reader io.Reader reader io.Reader
mreader *marshalReader mreader *marshalReader
writer io.Writer writer io.Writer
mwriter *marshalWriter mwriter *marshalWriter
wLock sync.RWMutex
closed bool closed bool
awaiting map[int]chan asyncResult awaiting map[int]chan asyncResult
nextId int nextId int
@ -94,12 +94,12 @@ func NewConnection(nodeID string, reader io.Reader, writer io.Writer, receiver M
// Index writes the list of file information to the connected peer node // Index writes the list of file information to the connected peer node
func (c *Connection) Index(idx []FileInfo) { func (c *Connection) Index(idx []FileInfo) {
c.wLock.Lock() c.Lock()
c.mwriter.writeHeader(header{0, c.nextId, messageTypeIndex}) c.mwriter.writeHeader(header{0, c.nextId, messageTypeIndex})
c.mwriter.writeIndex(idx) c.mwriter.writeIndex(idx)
err := c.flush() err := c.flush()
c.nextId = (c.nextId + 1) & 0xfff c.nextId = (c.nextId + 1) & 0xfff
c.wLock.Unlock() c.Unlock()
if err != nil || c.mwriter.err != nil { if err != nil || c.mwriter.err != nil {
c.close() c.close()
return return
@ -108,24 +108,24 @@ func (c *Connection) Index(idx []FileInfo) {
// Request returns the bytes for the specified block after fetching them from the connected peer. // Request returns the bytes for the specified block after fetching them from the connected peer.
func (c *Connection) Request(name string, offset uint64, size uint32, hash []byte) ([]byte, error) { func (c *Connection) Request(name string, offset uint64, size uint32, hash []byte) ([]byte, error) {
c.wLock.Lock() c.Lock()
rc := make(chan asyncResult) rc := make(chan asyncResult)
c.awaiting[c.nextId] = rc c.awaiting[c.nextId] = rc
c.mwriter.writeHeader(header{0, c.nextId, messageTypeRequest}) c.mwriter.writeHeader(header{0, c.nextId, messageTypeRequest})
c.mwriter.writeRequest(request{name, offset, size, hash}) c.mwriter.writeRequest(request{name, offset, size, hash})
if c.mwriter.err != nil { if c.mwriter.err != nil {
c.wLock.Unlock() c.Unlock()
c.close() c.close()
return nil, c.mwriter.err return nil, c.mwriter.err
} }
err := c.flush() err := c.flush()
if err != nil { if err != nil {
c.wLock.Unlock() c.Unlock()
c.close() c.close()
return nil, err return nil, err
} }
c.nextId = (c.nextId + 1) & 0xfff c.nextId = (c.nextId + 1) & 0xfff
c.wLock.Unlock() c.Unlock()
res, ok := <-rc res, ok := <-rc
if !ok { if !ok {
@ -134,22 +134,23 @@ func (c *Connection) Request(name string, offset uint64, size uint32, hash []byt
return res.val, res.err return res.val, res.err
} }
func (c *Connection) Ping() bool { func (c *Connection) Ping() (time.Duration, bool) {
c.wLock.Lock() c.Lock()
rc := make(chan asyncResult) rc := make(chan asyncResult)
c.awaiting[c.nextId] = rc c.awaiting[c.nextId] = rc
t0 := time.Now()
c.mwriter.writeHeader(header{0, c.nextId, messageTypePing}) c.mwriter.writeHeader(header{0, c.nextId, messageTypePing})
err := c.flush() err := c.flush()
if err != nil || c.mwriter.err != nil { if err != nil || c.mwriter.err != nil {
c.wLock.Unlock() c.Unlock()
c.close() c.close()
return false return 0, false
} }
c.nextId = (c.nextId + 1) & 0xfff c.nextId = (c.nextId + 1) & 0xfff
c.wLock.Unlock() c.Unlock()
_, ok := <-rc _, ok := <-rc
return ok return time.Since(t0), ok
} }
func (c *Connection) Stop() { func (c *Connection) Stop() {
@ -167,9 +168,9 @@ func (c *Connection) flush() error {
} }
func (c *Connection) close() { func (c *Connection) close() {
c.wLock.Lock() c.Lock()
if c.closed { if c.closed {
c.wLock.Unlock() c.Unlock()
return return
} }
c.closed = true c.closed = true
@ -177,14 +178,14 @@ func (c *Connection) close() {
close(ch) close(ch)
} }
c.awaiting = nil c.awaiting = nil
c.wLock.Unlock() c.Unlock()
c.receiver.Close(c.ID) c.receiver.Close(c.ID)
} }
func (c *Connection) isClosed() bool { func (c *Connection) isClosed() bool {
c.wLock.RLock() c.RLock()
defer c.wLock.RUnlock() defer c.RUnlock()
return c.closed return c.closed
} }
@ -201,9 +202,9 @@ func (c *Connection) readerLoop() {
break break
} }
c.wLock.Lock() c.Lock()
c.lastReceive = time.Now() c.lastReceive = time.Now()
c.wLock.Unlock() c.Unlock()
switch hdr.msgType { switch hdr.msgType {
case messageTypeIndex: case messageTypeIndex:
@ -226,41 +227,41 @@ func (c *Connection) readerLoop() {
if c.mreader.err != nil { if c.mreader.err != nil {
c.close() c.close()
} else { } else {
c.wLock.RLock() c.RLock()
rc, ok := c.awaiting[hdr.msgID] rc, ok := c.awaiting[hdr.msgID]
c.wLock.RUnlock() c.RUnlock()
if ok { if ok {
rc <- asyncResult{data, c.mreader.err} rc <- asyncResult{data, c.mreader.err}
close(rc) close(rc)
c.wLock.Lock() c.Lock()
delete(c.awaiting, hdr.msgID) delete(c.awaiting, hdr.msgID)
c.wLock.Unlock() c.Unlock()
} }
} }
case messageTypePing: case messageTypePing:
c.wLock.Lock() c.Lock()
c.mwriter.writeUint32(encodeHeader(header{0, hdr.msgID, messageTypePong})) c.mwriter.writeUint32(encodeHeader(header{0, hdr.msgID, messageTypePong}))
err := c.flush() err := c.flush()
c.wLock.Unlock() c.Unlock()
if err != nil || c.mwriter.err != nil { if err != nil || c.mwriter.err != nil {
c.close() c.close()
} }
case messageTypePong: case messageTypePong:
c.wLock.RLock() c.RLock()
rc, ok := c.awaiting[hdr.msgID] rc, ok := c.awaiting[hdr.msgID]
c.wLock.RUnlock() c.RUnlock()
if ok { if ok {
rc <- asyncResult{} rc <- asyncResult{}
close(rc) close(rc)
c.wLock.Lock() c.Lock()
delete(c.awaiting, hdr.msgID) delete(c.awaiting, hdr.msgID)
c.wLock.Unlock() c.Unlock()
} }
default: default:
@ -277,11 +278,11 @@ func (c *Connection) processRequest(msgID int) {
} else { } else {
go func() { go func() {
data, _ := c.receiver.Request(c.ID, req.name, req.offset, req.size, req.hash) data, _ := c.receiver.Request(c.ID, req.name, req.offset, req.size, req.hash)
c.wLock.Lock() c.Lock()
c.mwriter.writeUint32(encodeHeader(header{0, msgID, messageTypeResponse})) c.mwriter.writeUint32(encodeHeader(header{0, msgID, messageTypeResponse}))
c.mwriter.writeResponse(data) c.mwriter.writeResponse(data)
err := c.flush() err := c.flush()
c.wLock.Unlock() c.Unlock()
buffers.Put(data) buffers.Put(data)
if c.mwriter.err != nil || err != nil { if c.mwriter.err != nil || err != nil {
c.close() c.close()
@ -291,23 +292,24 @@ func (c *Connection) processRequest(msgID int) {
} }
func (c *Connection) pingerLoop() { func (c *Connection) pingerLoop() {
var rc = make(chan time.Duration) var rc = make(chan time.Duration, 1)
for !c.isClosed() { for !c.isClosed() {
c.wLock.RLock() c.RLock()
lr := c.lastReceive lr := c.lastReceive
c.wLock.RUnlock() c.RUnlock()
if time.Since(lr) > pingIdleTime { if time.Since(lr) > pingIdleTime {
go func() { go func() {
t0 := time.Now() t, ok := c.Ping()
c.Ping() if ok {
rc <- time.Since(t0) rc <- t
}
}() }()
select { select {
case lat := <-rc: case lat := <-rc:
c.wLock.Lock() c.Lock()
c.peerLatency = (c.peerLatency + lat) / 2 c.peerLatency = (c.peerLatency + lat) / 2
c.wLock.Unlock() c.Unlock()
case <-time.After(pingTimeout): case <-time.After(pingTimeout):
c.close() c.close()
} }
@ -326,8 +328,8 @@ type Statistics struct {
} }
func (c *Connection) Statistics() Statistics { func (c *Connection) Statistics() Statistics {
c.wLock.Lock() c.Lock()
defer c.wLock.Unlock() defer c.Unlock()
secs := time.Since(c.lastStatistics.At).Seconds() secs := time.Since(c.lastStatistics.At).Seconds()
stats := Statistics{ stats := Statistics{

View File

@ -46,10 +46,10 @@ func TestPing(t *testing.T) {
c0 := NewConnection("c0", ar, bw, nil) c0 := NewConnection("c0", ar, bw, nil)
c1 := NewConnection("c1", br, aw, nil) c1 := NewConnection("c1", br, aw, nil)
if !c0.Ping() { if _, ok := c0.Ping(); !ok {
t.Error("c0 ping failed") t.Error("c0 ping failed")
} }
if !c1.Ping() { if _, ok := c1.Ping(); !ok {
t.Error("c1 ping failed") t.Error("c1 ping failed")
} }
} }
@ -70,7 +70,7 @@ func TestPingErr(t *testing.T) {
c0 := NewConnection("c0", ar, ebw, m0) c0 := NewConnection("c0", ar, ebw, m0)
NewConnection("c1", br, eaw, m1) NewConnection("c1", br, eaw, m1)
res := c0.Ping() _, res := c0.Ping()
if (i < 4 || j < 4) && res { if (i < 4 || j < 4) && res {
t.Errorf("Unexpected ping success; i=%d, j=%d", i, j) t.Errorf("Unexpected ping success; i=%d, j=%d", i, j)
} else if (i >= 8 && j >= 8) && !res { } else if (i >= 8 && j >= 8) && !res {