go-libp2p-pubsub/floodsub.go

451 lines
9.9 KiB
Go
Raw Normal View History

2016-09-10 03:13:50 +00:00
package floodsub
import (
2016-09-10 23:03:53 +00:00
"context"
2016-09-11 03:47:12 +00:00
"encoding/binary"
"fmt"
"sync/atomic"
"time"
2016-09-13 02:59:24 +00:00
pb "github.com/libp2p/go-floodsub/pb"
2016-09-10 15:14:17 +00:00
2016-09-10 15:28:29 +00:00
logging "github.com/ipfs/go-log"
2016-10-05 19:47:20 +00:00
host "github.com/libp2p/go-libp2p-host"
inet "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
protocol "github.com/libp2p/go-libp2p-protocol"
2016-09-11 03:47:12 +00:00
timecache "github.com/whyrusleeping/timecache"
)
2016-09-10 03:13:50 +00:00
const ID = protocol.ID("/floodsub/1.0.0")
2016-09-10 03:13:50 +00:00
var log = logging.Logger("floodsub")
type PubSub struct {
host host.Host
2016-09-11 20:56:07 +00:00
// incoming messages from other peers
incoming chan *RPC
2016-09-11 20:56:07 +00:00
// messages we are publishing out to our peers
publish chan *Message
// addSub is a control channel for us to add and remove subscriptions
2016-10-19 23:01:06 +00:00
addSub chan *addSubReq
2016-09-11 20:56:07 +00:00
2016-10-19 23:01:06 +00:00
// get list of topics we are subscribed to
2016-09-14 22:11:41 +00:00
getTopics chan *topicReq
2016-10-19 23:01:06 +00:00
// get chan of peers we are connected to
getPeers chan *listPeerReq
2016-10-19 23:01:06 +00:00
// send subscription here to cancel it
cancelCh chan *Subscription
2016-09-14 21:12:20 +00:00
2016-09-11 20:56:07 +00:00
// a notification channel for incoming streams from other peers
newPeers chan inet.Stream
2016-09-11 20:56:07 +00:00
// a notification channel for when our peers die
peerDead chan peer.ID
2016-09-11 20:56:07 +00:00
// The set of topics we are subscribed to
2016-10-19 23:01:06 +00:00
myTopics map[string]map[*Subscription]struct{}
2016-09-11 20:56:07 +00:00
// topics tracks which topics each of our peers are subscribed to
topics map[string]map[peer.ID]struct{}
2016-09-11 03:47:12 +00:00
peers map[peer.ID]chan *RPC
seenMessages *timecache.TimeCache
2016-09-10 23:03:53 +00:00
ctx context.Context
// atomic counter for seqnos
counter uint64
}
type Message struct {
2016-09-10 15:14:17 +00:00
*pb.Message
}
2016-09-10 15:14:17 +00:00
func (m *Message) GetFrom() peer.ID {
return peer.ID(m.Message.GetFrom())
}
type RPC struct {
2016-09-10 15:14:17 +00:00
pb.RPC
// unexported on purpose, not sending this over the wire
from peer.ID
}
2016-10-20 11:23:38 +00:00
// NewFloodSub returns a new FloodSub management object
2016-09-10 23:03:53 +00:00
func NewFloodSub(ctx context.Context, h host.Host) *PubSub {
ps := &PubSub{
2016-09-11 03:47:12 +00:00
host: h,
ctx: ctx,
incoming: make(chan *RPC, 32),
publish: make(chan *Message),
newPeers: make(chan inet.Stream),
peerDead: make(chan peer.ID),
2016-10-19 23:01:06 +00:00
cancelCh: make(chan *Subscription),
getPeers: make(chan *listPeerReq),
2016-10-19 23:01:06 +00:00
addSub: make(chan *addSubReq),
2016-09-14 22:11:41 +00:00
getTopics: make(chan *topicReq),
2016-10-19 23:01:06 +00:00
myTopics: make(map[string]map[*Subscription]struct{}),
2016-09-11 03:47:12 +00:00
topics: make(map[string]map[peer.ID]struct{}),
peers: make(map[peer.ID]chan *RPC),
seenMessages: timecache.NewTimeCache(time.Second * 30),
}
h.SetStreamHandler(ID, ps.handleNewStream)
h.Network().Notify((*PubSubNotif)(ps))
2016-09-10 23:03:53 +00:00
go ps.processLoop(ctx)
return ps
}
2016-10-20 11:23:38 +00:00
// processLoop handles all inputs arriving on the channels
2016-09-10 23:03:53 +00:00
func (p *PubSub) processLoop(ctx context.Context) {
defer func() {
// Clean up go routines.
for _, ch := range p.peers {
close(ch)
}
p.peers = nil
p.topics = nil
}()
for {
select {
case s := <-p.newPeers:
pid := s.Conn().RemotePeer()
ch, ok := p.peers[pid]
if ok {
log.Error("already have connection to peer: ", pid)
close(ch)
}
messages := make(chan *RPC, 32)
2016-09-10 23:03:53 +00:00
go p.handleSendingMessages(ctx, s, messages)
messages <- p.getHelloPacket()
p.peers[pid] = messages
case pid := <-p.peerDead:
ch, ok := p.peers[pid]
if ok {
close(ch)
}
delete(p.peers, pid)
for _, t := range p.topics {
delete(t, pid)
}
2016-09-14 22:11:41 +00:00
case treq := <-p.getTopics:
var out []string
for t := range p.myTopics {
out = append(out, t)
2016-09-14 22:11:41 +00:00
}
treq.resp <- out
2016-10-19 23:01:06 +00:00
case sub := <-p.cancelCh:
p.handleRemoveSubscription(sub)
case sub := <-p.addSub:
2016-10-19 23:01:06 +00:00
p.handleAddSubscription(sub)
case preq := <-p.getPeers:
tmap, ok := p.topics[preq.topic]
if preq.topic != "" && !ok {
preq.resp <- nil
continue
}
var peers []peer.ID
for p := range p.peers {
if preq.topic != "" {
_, ok := tmap[p]
if !ok {
continue
}
}
peers = append(peers, p)
}
preq.resp <- peers
case rpc := <-p.incoming:
err := p.handleIncomingRPC(rpc)
if err != nil {
log.Error("handling RPC: ", err)
2016-09-11 20:56:07 +00:00
continue
}
2016-09-11 03:47:12 +00:00
case msg := <-p.publish:
p.maybePublishMessage(p.host.ID(), msg.Message)
2016-09-10 23:03:53 +00:00
case <-ctx.Done():
log.Info("pubsub processloop shutting down")
return
}
}
}
2016-09-10 03:13:50 +00:00
2016-10-20 11:23:38 +00:00
// handleRemoveSubscription removes Subscription sub from bookeeping.
// If this was the last Subscription for a given topic, it will also announce
// that this node is not subscribing to this topic anymore.
// Only called from processLoop.
2016-10-19 23:01:06 +00:00
func (p *PubSub) handleRemoveSubscription(sub *Subscription) {
subs := p.myTopics[sub.topic]
if subs == nil {
return
2016-09-11 03:47:12 +00:00
}
2016-09-10 03:13:50 +00:00
2016-10-19 23:01:06 +00:00
sub.err = fmt.Errorf("subscription cancelled by calling sub.Cancel()")
close(sub.ch)
delete(subs, sub)
2016-09-10 03:13:50 +00:00
2016-10-19 23:01:06 +00:00
if len(subs) == 0 {
delete(p.myTopics, sub.topic)
2016-10-19 23:01:06 +00:00
p.announce(sub.topic, false)
}
}
2016-09-11 03:47:12 +00:00
2016-10-20 11:23:38 +00:00
// handleAddSubscription adds a Subscription for a particular topic. If it is
// the first Subscription for the topic, it will announce that this node
// subscribes to the topic.
// Only called from processLoop.
2016-10-19 23:01:06 +00:00
func (p *PubSub) handleAddSubscription(req *addSubReq) {
subs := p.myTopics[req.topic]
// announce we want this topic
if len(subs) == 0 {
p.announce(req.topic, true)
}
// make new if not there
if subs == nil {
p.myTopics[req.topic] = make(map[*Subscription]struct{})
subs = p.myTopics[req.topic]
}
sub := &Subscription{
ch: make(chan *Message, 32),
topic: req.topic,
cancelCh: p.cancelCh,
}
p.myTopics[sub.topic][sub] = struct{}{}
req.resp <- sub
}
2016-10-20 11:23:38 +00:00
// announce announces whether or not this node is interested in a given topic
// Only called from processLoop.
2016-10-19 23:01:06 +00:00
func (p *PubSub) announce(topic string, sub bool) {
subopt := &pb.RPC_SubOpts{
Topicid: &topic,
Subscribe: &sub,
2016-09-11 03:47:12 +00:00
}
2016-09-11 20:56:07 +00:00
out := rpcWithSubs(subopt)
for pid, peer := range p.peers {
select {
case peer <- out:
default:
log.Infof("dropping announce message to peer %s: queue full", pid)
}
2016-09-11 03:47:12 +00:00
}
2016-09-10 03:13:50 +00:00
}
2016-10-20 11:23:38 +00:00
// notifySubs sends a given message to all corresponding subscribbers.
// Only called from processLoop.
2016-09-11 20:56:07 +00:00
func (p *PubSub) notifySubs(msg *pb.Message) {
for _, topic := range msg.GetTopicIDs() {
2016-10-19 23:01:06 +00:00
subs := p.myTopics[topic]
for f := range subs {
f.ch <- &Message{msg}
2016-09-11 20:56:07 +00:00
}
}
}
2016-10-20 11:23:38 +00:00
// seenMessage returns whether we already saw this message before
2016-09-11 03:47:12 +00:00
func (p *PubSub) seenMessage(id string) bool {
return p.seenMessages.Has(id)
}
2016-10-20 11:23:38 +00:00
// markSeen marks a message as seen such that seenMessage returns `true' for the given id
2016-09-11 03:47:12 +00:00
func (p *PubSub) markSeen(id string) {
p.seenMessages.Add(id)
}
2016-10-20 11:23:38 +00:00
// subscribedToMessage returns whether we are subscribed to one of the topics
// of a given message
2016-09-11 20:56:07 +00:00
func (p *PubSub) subscribedToMsg(msg *pb.Message) bool {
if len(p.myTopics) == 0 {
return false
}
2016-09-11 20:56:07 +00:00
for _, t := range msg.GetTopicIDs() {
if _, ok := p.myTopics[t]; ok {
return true
}
}
return false
}
func (p *PubSub) handleIncomingRPC(rpc *RPC) error {
2016-09-11 03:47:12 +00:00
for _, subopt := range rpc.GetSubscriptions() {
t := subopt.GetTopicid()
if subopt.GetSubscribe() {
tmap, ok := p.topics[t]
if !ok {
tmap = make(map[peer.ID]struct{})
p.topics[t] = tmap
}
tmap[rpc.from] = struct{}{}
2016-09-11 03:47:12 +00:00
} else {
tmap, ok := p.topics[t]
if !ok {
2016-09-11 03:47:12 +00:00
continue
}
delete(tmap, rpc.from)
}
2016-09-11 03:47:12 +00:00
}
2016-09-10 03:13:50 +00:00
2016-09-11 03:47:12 +00:00
for _, pmsg := range rpc.GetPublish() {
2016-09-11 20:56:07 +00:00
if !p.subscribedToMsg(pmsg) {
log.Warning("received message we didn't subscribe to. Dropping.")
2016-09-11 03:47:12 +00:00
continue
}
2016-09-11 20:56:07 +00:00
p.maybePublishMessage(rpc.from, pmsg)
}
return nil
}
2016-10-20 11:23:38 +00:00
// msgID returns a unique ID of the passed Message
func msgID(pmsg *pb.Message) string {
return string(pmsg.GetFrom()) + string(pmsg.GetSeqno())
}
2016-09-11 20:56:07 +00:00
func (p *PubSub) maybePublishMessage(from peer.ID, pmsg *pb.Message) {
id := msgID(pmsg)
2016-09-11 20:56:07 +00:00
if p.seenMessage(id) {
return
}
p.markSeen(id)
p.notifySubs(pmsg)
err := p.publishMessage(from, pmsg)
if err != nil {
log.Error("publish message: ", err)
}
}
2016-09-11 03:47:12 +00:00
func (p *PubSub) publishMessage(from peer.ID, msg *pb.Message) error {
tosend := make(map[peer.ID]struct{})
for _, topic := range msg.GetTopicIDs() {
tmap, ok := p.topics[topic]
if !ok {
continue
}
2016-09-11 03:47:12 +00:00
for p, _ := range tmap {
tosend[p] = struct{}{}
}
}
out := rpcWithMessages(msg)
for pid := range tosend {
2016-09-11 03:47:12 +00:00
if pid == from || pid == peer.ID(msg.GetFrom()) {
continue
}
mch, ok := p.peers[pid]
if !ok {
continue
}
select {
case mch <- out:
default:
2017-08-30 02:42:33 +00:00
log.Infof("dropping message to peer %s: queue full", pid)
// Drop it. The peer is too slow.
}
}
return nil
}
2016-10-19 23:01:06 +00:00
type addSubReq struct {
2016-09-11 03:47:12 +00:00
topic string
2016-10-19 23:01:06 +00:00
resp chan *Subscription
}
2016-10-20 11:23:38 +00:00
// Subscribe returns a new Subscription for the given topic
func (p *PubSub) Subscribe(topic string) (*Subscription, error) {
td := pb.TopicDescriptor{Name: &topic}
return p.SubscribeByTopicDescriptor(&td)
}
// SubscribeByTopicDescriptor lets you subscribe a topic using a pb.TopicDescriptor
func (p *PubSub) SubscribeByTopicDescriptor(td *pb.TopicDescriptor) (*Subscription, error) {
if td.GetAuth().GetMode() != pb.TopicDescriptor_AuthOpts_NONE {
return nil, fmt.Errorf("auth mode not yet supported")
}
if td.GetEnc().GetMode() != pb.TopicDescriptor_EncOpts_NONE {
return nil, fmt.Errorf("encryption mode not yet supported")
}
out := make(chan *Subscription, 1)
p.addSub <- &addSubReq{
topic: td.GetName(),
resp: out,
}
return <-out, nil
}
2016-10-19 23:01:06 +00:00
type topicReq struct {
resp chan []string
}
2016-10-20 11:23:38 +00:00
// GetTopics returns the topics this node is subscribed to
2016-10-19 23:01:06 +00:00
func (p *PubSub) GetTopics() []string {
out := make(chan []string, 1)
p.getTopics <- &topicReq{resp: out}
return <-out
}
2016-10-20 11:23:38 +00:00
// Publish publishes data under the given topic
func (p *PubSub) Publish(topic string, data []byte) error {
seqno := make([]byte, 16)
counter := atomic.AddUint64(&p.counter, 1)
binary.BigEndian.PutUint64(seqno[:8], uint64(time.Now().UnixNano()))
binary.BigEndian.PutUint64(seqno[8:], counter)
2016-09-11 03:47:12 +00:00
p.publish <- &Message{
&pb.Message{
Data: data,
TopicIDs: []string{topic},
From: []byte(p.host.ID()),
2016-09-11 03:47:12 +00:00
Seqno: seqno,
},
}
return nil
}
type listPeerReq struct {
resp chan []peer.ID
topic string
}
2016-10-20 11:23:38 +00:00
// ListPeers returns a list of peers we are connected to.
func (p *PubSub) ListPeers(topic string) []peer.ID {
out := make(chan []peer.ID)
p.getPeers <- &listPeerReq{
resp: out,
topic: topic,
}
return <-out
}