Skip to content

Commit

Permalink
add base repo files
Browse files Browse the repository at this point in the history
  • Loading branch information
whyrusleeping committed Jul 10, 2017
1 parent 2e5c85b commit 2e60f48
Show file tree
Hide file tree
Showing 5 changed files with 168 additions and 47 deletions.
24 changes: 24 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
os:
- linux
- osx

language: go

go:
- 1.8

install: true

before_install:
- make deps

script:
- go vet
- $GOPATH/bin/goveralls -service="travis-ci"

cache:
directories:
- $GOPATH/src/gx

notifications:
email: false
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Whyrusleeping

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
17 changes: 17 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
all: deps

gx:
go get github.com/whyrusleeping/gx
go get github.com/whyrusleeping/gx-go

covertools:
go get github.com/mattn/goveralls
go get golang.org/x/tools/cmd/cover

deps: gx covertools
gx --verbose install --global
gx-go rewrite

publish:
gx-go rewrite --undo

41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
go-libp2p-connmgr
==================

[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io)
[![](https://img.shields.io/badge/project-IPFS-blue.svg?style=flat-square)](http://libp2p.io/)
[![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23ipfs)
[![Coverage Status](https://coveralls.io/repos/github/libp2p/go-libp2p-connmgr/badge.svg?branch=master)](https://coveralls.io/github/libp2p/go-libp2p-connmgr?branch=master)
[![Travis CI](https://travis-ci.org/libp2p/go-libp2p-connmgr.svg?branch=master)](https://travis-ci.org/libp2p/go-libp2p-connmgr)

> A package to help manage connections in go-libp2p

## Table of Contents

- [Install](#install)
- [Usage](#usage)
- [API](#api)
- [Contribute](#contribute)
- [License](#license)

## Install

```sh
make install
```

## Examples

```go
// TODO:
```

## Contribute

PRs are welcome!

Small note: If editing the Readme, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.

## License

MIT © Whyrusleeping
112 changes: 65 additions & 47 deletions connmgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import (
"sync"
"time"

inet "gx/ipfs/QmRscs8KxrSmSv4iuevHv8JfuUzHBMoqiaHzxfDRiksd6e/go-libp2p-net"
logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
ma "gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr"
logging "github.com/ipfs/go-log"
inet "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
ma "github.com/multiformats/go-multiaddr"
)

var log = logging.Logger("connmgr")
Expand All @@ -19,53 +20,50 @@ type ConnManager struct {

GracePeriod time.Duration

conns map[inet.Conn]connInfo
peers map[peer.ID]peerInfo
connCount int

lk sync.Mutex

lastTrim time.Time
}

func NewConnManager(low, hi int) *ConnManager {
return &ConnManager{
HighWater: hi,
LowWater: low,
GracePeriod: time.Second * 10,
conns: make(map[inet.Conn]connInfo),
peers: make(map[peer.ID]peerInfo),
}
}

type connInfo struct {
tags map[string]int
value int
c inet.Conn
closed bool
type peerInfo struct {
tags map[string]int
value int

conns map[inet.Conn]time.Time

firstSeen time.Time
}

func (cm *ConnManager) TrimOpenConns(ctx context.Context) {
defer log.EventBegin(ctx, "connCleanup").Done()
cm.lk.Lock()
defer cm.lk.Unlock()
defer log.EventBegin(ctx, "connCleanup").Done()
cm.lastTrim = time.Now()

if len(cm.conns) < cm.LowWater {
if len(cm.peers) < cm.LowWater {
log.Info("open connection count below limit")
return
}

var infos []connInfo
var infos []peerInfo

for _, inf := range cm.conns {
for _, inf := range cm.peers {
infos = append(infos, inf)
}

sort.Slice(infos, func(i, j int) bool {
if infos[i].closed {
return true
}
if infos[j].closed {
return false
}

return infos[i].value < infos[j].value
})

Expand All @@ -76,43 +74,45 @@ func (cm *ConnManager) TrimOpenConns(ctx context.Context) {
continue
}

log.Info("closing conn: ", inf.c.RemotePeer())
log.Event(ctx, "closeConn", inf.c.RemotePeer())
inf.c.Close()
inf.closed = true
// TODO: if a peer has more than one connection, maybe only close one?
for c, _ := range inf.conns {
log.Info("closing conn: ", c.RemotePeer())
log.Event(ctx, "closeConn", c.RemotePeer())
c.Close()
}
}

if len(cm.conns) > cm.HighWater {
if len(cm.peers) > cm.HighWater {
log.Error("still over high water mark after trimming connections")
}
}

func (cm *ConnManager) TagConn(c inet.Conn, tag string, val int) {
func (cm *ConnManager) TagConn(p peer.ID, tag string, val int) {
cm.lk.Lock()
defer cm.lk.Unlock()

ci, ok := cm.conns[c]
pi, ok := cm.peers[p]
if !ok {
log.Error("tried to tag untracked conn: ", c.RemotePeer())
log.Error("tried to tag conn from untracked peer: ", p)
return
}

ci.value += (val - ci.tags[tag])
ci.tags[tag] = val
pi.value += (val - pi.tags[tag])
pi.tags[tag] = val
}

func (cm *ConnManager) UntagConn(c inet.Conn, tag string) {
func (cm *ConnManager) UntagConn(p peer.ID, tag string) {
cm.lk.Lock()
defer cm.lk.Unlock()

ci, ok := cm.conns[c]
pi, ok := cm.peers[p]
if !ok {
log.Error("tried to remove tag on untracked conn: ", c.RemotePeer())
log.Error("tried to remove tag from untracked peer: ", p)
return
}

ci.value -= ci.tags[tag]
delete(ci.tags, tag)
pi.value -= pi.tags[tag]
delete(pi.tags, tag)
}

func (cm *ConnManager) Notifee() *cmNotifee {
Expand All @@ -131,21 +131,29 @@ func (nn *cmNotifee) Connected(n inet.Network, c inet.Conn) {
cm.lk.Lock()
defer cm.lk.Unlock()

cinfo, ok := cm.conns[c]
pinfo, ok := cm.peers[c.RemotePeer()]
if !ok {
pinfo = peerInfo{
firstSeen: time.Now(),
tags: make(map[string]int),
conns: make(map[inet.Conn]time.Time),
}
cm.peers[c.RemotePeer()] = pinfo
}

_, ok = pinfo.conns[c]
if ok {
log.Error("received connected notification for conn we are already tracking: ", c.RemotePeer())
return
}

cinfo = connInfo{
firstSeen: time.Now(),
tags: make(map[string]int),
c: c,
}
cm.conns[c] = cinfo
pinfo.conns[c] = time.Now()
cm.connCount++

if len(cm.conns) > nn.HighWater {
go cm.TrimOpenConns(context.Background())
if cm.connCount > nn.HighWater {
if cm.lastTrim.IsZero() || time.Since(cm.lastTrim) > time.Second*10 {
go cm.TrimOpenConns(context.Background())
}
}
}

Expand All @@ -155,13 +163,23 @@ func (nn *cmNotifee) Disconnected(n inet.Network, c inet.Conn) {
cm.lk.Lock()
defer cm.lk.Unlock()

_, ok := cm.conns[c]
cinf, ok := cm.peers[c.RemotePeer()]
if !ok {
log.Error("received disconnected notification for peer we are not tracking: ", c.RemotePeer())
return
}

_, ok = cinf.conns[c]
if !ok {
log.Error("received disconnected notification for conn we are not tracking: ", c.RemotePeer())
return
}

delete(cm.conns, c)
delete(cinf.conns, c)
cm.connCount--
if len(cinf.conns) == 0 {
delete(cm.peers, c.RemotePeer())
}
}

func (nn *cmNotifee) Listen(n inet.Network, addr ma.Multiaddr) {}
Expand Down

0 comments on commit 2e60f48

Please sign in to comment.