tracker/storage/memory/peer_store.go

456 lines
10 KiB
Go
Raw Normal View History

2016-08-10 03:34:16 +02:00
package memory
import (
"encoding/binary"
"errors"
2016-08-10 03:34:16 +02:00
"net"
"runtime"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
2016-08-17 03:42:08 +02:00
"github.com/chihaya/chihaya/bittorrent"
"github.com/chihaya/chihaya/storage"
2016-08-10 03:34:16 +02:00
)
func init() {
prometheus.MustRegister(promGCDurationMilliseconds)
prometheus.MustRegister(promInfohashesCount)
}
var promGCDurationMilliseconds = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "chihaya_storage_gc_duration_milliseconds",
Help: "The time it takes to perform storage garbage collection",
Buckets: prometheus.ExponentialBuckets(9.375, 2, 10),
})
var promInfohashesCount = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "chihaya_storage_infohashes_count",
2017-02-01 02:58:08 +01:00
Help: "The number of infohashes tracked",
})
// recordGCDuration records the duration of a GC sweep.
func recordGCDuration(duration time.Duration) {
promGCDurationMilliseconds.Observe(float64(duration.Nanoseconds()) / float64(time.Millisecond))
}
// recordInfohashesDelta records a change in the number of Infohashes tracked.
func recordInfohashesDelta(delta float64) {
promInfohashesCount.Add(delta)
}
// ErrInvalidGCInterval is returned for a GarbageCollectionInterval that is
// less than or equal to zero.
var ErrInvalidGCInterval = errors.New("invalid garbage collection interval")
2016-08-12 02:37:31 +02:00
// Config holds the configuration of a memory PeerStore.
2016-08-10 03:34:16 +02:00
type Config struct {
GarbageCollectionInterval time.Duration `yaml:"gc_interval"`
PeerLifetime time.Duration `yaml:"peer_lifetime"`
ShardCount int `yaml:"shard_count"`
2016-08-10 03:34:16 +02:00
}
// New creates a new PeerStore backed by memory.
2016-08-10 03:34:16 +02:00
func New(cfg Config) (storage.PeerStore, error) {
shardCount := 1
if cfg.ShardCount > 0 {
shardCount = cfg.ShardCount
}
if cfg.GarbageCollectionInterval <= 0 {
return nil, ErrInvalidGCInterval
}
ps := &peerStore{
2016-11-28 20:55:04 +01:00
shards: make([]*peerShard, shardCount*2),
closed: make(chan struct{}),
}
for i := 0; i < shardCount*2; i++ {
ps.shards[i] = &peerShard{swarms: make(map[bittorrent.InfoHash]swarm)}
2016-08-10 03:34:16 +02:00
}
go func() {
for {
select {
case <-ps.closed:
return
case <-time.After(cfg.GarbageCollectionInterval):
before := time.Now().Add(-cfg.PeerLifetime)
log.Debugln("memory: purging peers with no announces since", before)
ps.collectGarbage(before)
}
}
}()
return ps, nil
2016-08-10 03:34:16 +02:00
}
type serializedPeer string
type peerShard struct {
swarms map[bittorrent.InfoHash]swarm
2016-08-10 03:34:16 +02:00
sync.RWMutex
}
type swarm struct {
// map serialized peer to mtime
seeders map[serializedPeer]int64
leechers map[serializedPeer]int64
}
type peerStore struct {
2016-11-28 20:55:04 +01:00
shards []*peerShard
closed chan struct{}
2016-08-10 03:34:16 +02:00
}
var _ storage.PeerStore = &peerStore{}
2016-11-28 20:55:04 +01:00
func (s *peerStore) shardIndex(infoHash bittorrent.InfoHash, af bittorrent.AddressFamily) uint32 {
2016-09-08 15:40:31 +02:00
// There are twice the amount of shards specified by the user, the first
// half is dedicated to IPv4 swarms and the second half is dedicated to
// IPv6 swarms.
idx := binary.BigEndian.Uint32(infoHash[:4]) % (uint32(len(s.shards)) / 2)
2016-11-28 20:55:04 +01:00
if af == bittorrent.IPv6 {
2016-09-08 15:40:31 +02:00
idx += uint32(len(s.shards) / 2)
}
return idx
2016-08-10 03:34:16 +02:00
}
func newPeerKey(p bittorrent.Peer) serializedPeer {
2016-11-28 20:55:04 +01:00
b := make([]byte, 20+2+len(p.IP.IP))
2016-08-10 03:34:16 +02:00
copy(b[:20], p.ID[:])
binary.BigEndian.PutUint16(b[20:22], p.Port)
2016-11-28 20:55:04 +01:00
copy(b[22:], p.IP.IP)
2016-08-10 03:34:16 +02:00
return serializedPeer(b)
}
func decodePeerKey(pk serializedPeer) bittorrent.Peer {
2016-11-28 20:55:04 +01:00
peer := bittorrent.Peer{
2016-08-10 03:34:16 +02:00
ID: bittorrent.PeerIDFromString(string(pk[:20])),
Port: binary.BigEndian.Uint16([]byte(pk[20:22])),
2016-11-28 20:55:04 +01:00
IP: bittorrent.IP{IP: net.IP(pk[22:])}}
if ip := peer.IP.To4(); ip != nil {
peer.IP.IP = ip
peer.IP.AddressFamily = bittorrent.IPv4
} else if len(peer.IP.IP) == net.IPv6len { // implies toReturn.IP.To4() == nil
peer.IP.AddressFamily = bittorrent.IPv6
} else {
panic("IP is neither v4 nor v6")
2016-08-10 03:34:16 +02:00
}
2016-11-28 20:55:04 +01:00
return peer
2016-08-10 03:34:16 +02:00
}
func (s *peerStore) PutSeeder(ih bittorrent.InfoHash, p bittorrent.Peer) error {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
pk := newPeerKey(p)
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, p.IP.AddressFamily)]
2016-08-10 03:34:16 +02:00
shard.Lock()
if _, ok := shard.swarms[ih]; !ok {
shard.swarms[ih] = swarm{
2016-08-10 03:34:16 +02:00
seeders: make(map[serializedPeer]int64),
leechers: make(map[serializedPeer]int64),
}
recordInfohashesDelta(1)
2016-08-10 03:34:16 +02:00
}
shard.swarms[ih].seeders[pk] = time.Now().UnixNano()
2016-08-10 03:34:16 +02:00
shard.Unlock()
return nil
}
func (s *peerStore) DeleteSeeder(ih bittorrent.InfoHash, p bittorrent.Peer) error {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
pk := newPeerKey(p)
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, p.IP.AddressFamily)]
2016-08-10 03:34:16 +02:00
shard.Lock()
if _, ok := shard.swarms[ih]; !ok {
2016-08-10 03:34:16 +02:00
shard.Unlock()
return storage.ErrResourceDoesNotExist
}
if _, ok := shard.swarms[ih].seeders[pk]; !ok {
2016-08-10 03:34:16 +02:00
shard.Unlock()
return storage.ErrResourceDoesNotExist
}
delete(shard.swarms[ih].seeders, pk)
2016-08-10 03:34:16 +02:00
if len(shard.swarms[ih].seeders)|len(shard.swarms[ih].leechers) == 0 {
delete(shard.swarms, ih)
recordInfohashesDelta(-1)
2016-08-10 03:34:16 +02:00
}
shard.Unlock()
return nil
}
func (s *peerStore) PutLeecher(ih bittorrent.InfoHash, p bittorrent.Peer) error {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
pk := newPeerKey(p)
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, p.IP.AddressFamily)]
2016-08-10 03:34:16 +02:00
shard.Lock()
if _, ok := shard.swarms[ih]; !ok {
shard.swarms[ih] = swarm{
2016-08-10 03:34:16 +02:00
seeders: make(map[serializedPeer]int64),
leechers: make(map[serializedPeer]int64),
}
recordInfohashesDelta(1)
2016-08-10 03:34:16 +02:00
}
shard.swarms[ih].leechers[pk] = time.Now().UnixNano()
2016-08-10 03:34:16 +02:00
shard.Unlock()
return nil
}
func (s *peerStore) DeleteLeecher(ih bittorrent.InfoHash, p bittorrent.Peer) error {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
pk := newPeerKey(p)
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, p.IP.AddressFamily)]
2016-08-10 03:34:16 +02:00
shard.Lock()
if _, ok := shard.swarms[ih]; !ok {
2016-08-10 03:34:16 +02:00
shard.Unlock()
return storage.ErrResourceDoesNotExist
}
if _, ok := shard.swarms[ih].leechers[pk]; !ok {
2016-08-10 03:34:16 +02:00
shard.Unlock()
return storage.ErrResourceDoesNotExist
}
delete(shard.swarms[ih].leechers, pk)
2016-08-10 03:34:16 +02:00
if len(shard.swarms[ih].seeders)|len(shard.swarms[ih].leechers) == 0 {
delete(shard.swarms, ih)
recordInfohashesDelta(-1)
2016-08-10 03:34:16 +02:00
}
shard.Unlock()
return nil
}
func (s *peerStore) GraduateLeecher(ih bittorrent.InfoHash, p bittorrent.Peer) error {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
pk := newPeerKey(p)
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, p.IP.AddressFamily)]
2016-08-10 03:34:16 +02:00
shard.Lock()
if _, ok := shard.swarms[ih]; !ok {
shard.swarms[ih] = swarm{
2016-08-10 03:34:16 +02:00
seeders: make(map[serializedPeer]int64),
leechers: make(map[serializedPeer]int64),
}
recordInfohashesDelta(1)
2016-08-10 03:34:16 +02:00
}
delete(shard.swarms[ih].leechers, pk)
2016-08-10 03:34:16 +02:00
shard.swarms[ih].seeders[pk] = time.Now().UnixNano()
2016-08-10 03:34:16 +02:00
shard.Unlock()
return nil
}
func (s *peerStore) AnnouncePeers(ih bittorrent.InfoHash, seeder bool, numWant int, announcer bittorrent.Peer) (peers []bittorrent.Peer, err error) {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, announcer.IP.AddressFamily)]
2016-08-10 03:34:16 +02:00
shard.RLock()
if _, ok := shard.swarms[ih]; !ok {
2016-08-10 03:34:16 +02:00
shard.RUnlock()
return nil, storage.ErrResourceDoesNotExist
}
if seeder {
// Append leechers as possible.
leechers := shard.swarms[ih].leechers
2016-08-10 03:34:16 +02:00
for p := range leechers {
decodedPeer := decodePeerKey(p)
if numWant == 0 {
break
}
peers = append(peers, decodedPeer)
numWant--
}
} else {
// Append as many seeders as possible.
seeders := shard.swarms[ih].seeders
2016-08-10 03:34:16 +02:00
for p := range seeders {
decodedPeer := decodePeerKey(p)
if numWant == 0 {
break
}
peers = append(peers, decodedPeer)
numWant--
}
// Append leechers until we reach numWant.
leechers := shard.swarms[ih].leechers
2016-08-10 03:34:16 +02:00
if numWant > 0 {
for p := range leechers {
decodedPeer := decodePeerKey(p)
if numWant == 0 {
break
}
if decodedPeer.Equal(announcer) {
continue
}
peers = append(peers, decodedPeer)
numWant--
}
}
}
shard.RUnlock()
return
}
2016-11-28 20:55:04 +01:00
func (s *peerStore) ScrapeSwarm(ih bittorrent.InfoHash, addressFamily bittorrent.AddressFamily) (resp bittorrent.Scrape) {
2016-09-08 15:40:31 +02:00
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
2017-01-29 18:47:07 +01:00
resp.InfoHash = ih
2016-11-28 20:55:04 +01:00
shard := s.shards[s.shardIndex(ih, addressFamily)]
2016-09-08 15:40:31 +02:00
shard.RLock()
if _, ok := shard.swarms[ih]; !ok {
shard.RUnlock()
return
}
resp.Incomplete = uint32(len(shard.swarms[ih].leechers))
resp.Complete = uint32(len(shard.swarms[ih].seeders))
shard.RUnlock()
return
}
// collectGarbage deletes all Peers from the PeerStore which are older than the
// cutoff time.
//
// This function must be able to execute while other methods on this interface
// are being executed in parallel.
func (s *peerStore) collectGarbage(cutoff time.Time) error {
select {
case <-s.closed:
panic("attempted to interact with stopped memory store")
default:
}
var ihDelta float64
cutoffUnix := cutoff.UnixNano()
start := time.Now()
for _, shard := range s.shards {
shard.RLock()
var infohashes []bittorrent.InfoHash
for ih := range shard.swarms {
infohashes = append(infohashes, ih)
}
shard.RUnlock()
runtime.Gosched()
for _, ih := range infohashes {
shard.Lock()
if _, stillExists := shard.swarms[ih]; !stillExists {
shard.Unlock()
runtime.Gosched()
continue
}
for pk, mtime := range shard.swarms[ih].leechers {
if mtime <= cutoffUnix {
delete(shard.swarms[ih].leechers, pk)
}
}
for pk, mtime := range shard.swarms[ih].seeders {
if mtime <= cutoffUnix {
delete(shard.swarms[ih].seeders, pk)
}
}
if len(shard.swarms[ih].seeders)|len(shard.swarms[ih].leechers) == 0 {
delete(shard.swarms, ih)
ihDelta--
}
shard.Unlock()
runtime.Gosched()
}
runtime.Gosched()
}
recordGCDuration(time.Since(start))
recordInfohashesDelta(ihDelta)
return nil
}
2016-08-10 03:34:16 +02:00
func (s *peerStore) Stop() <-chan error {
toReturn := make(chan error)
go func() {
shards := make([]*peerShard, len(s.shards))
for i := 0; i < len(s.shards); i++ {
shards[i] = &peerShard{swarms: make(map[bittorrent.InfoHash]swarm)}
2016-08-10 03:34:16 +02:00
}
s.shards = shards
close(s.closed)
close(toReturn)
}()
return toReturn
}