peermanager.go 4.11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
package bitswap

import (
	"sync"

	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	engine "github.com/ipfs/go-ipfs/exchange/bitswap/decision"
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	u "github.com/ipfs/go-ipfs/util"
)

type PeerManager struct {
	receiver bsnet.Receiver

	incoming   chan *msgPair
	connect    chan peer.ID
	disconnect chan peer.ID

	peers map[peer.ID]*msgQueue

	network bsnet.BitSwapNetwork
}

func NewPeerManager(network bsnet.BitSwapNetwork) *PeerManager {
	return &PeerManager{
		incoming:   make(chan *msgPair, 10),
		connect:    make(chan peer.ID, 10),
		disconnect: make(chan peer.ID, 10),
		peers:      make(map[peer.ID]*msgQueue),
		network:    network,
	}
}

type msgPair struct {
	to  peer.ID
	msg bsmsg.BitSwapMessage
}

type cancellation struct {
	who peer.ID
	blk u.Key
}

type msgQueue struct {
	p peer.ID

Jeromy's avatar
Jeromy committed
49 50
	outlk sync.Mutex
	out   bsmsg.BitSwapMessage
51 52 53 54 55

	work chan struct{}
	done chan struct{}
}

Jeromy's avatar
Jeromy committed
56
func (pm *PeerManager) SendBlock(ctx context.Context, env *engine.Envelope) {
57 58 59 60 61 62
	// Blocks need to be sent synchronously to maintain proper backpressure
	// throughout the network stack
	defer env.Sent()

	msg := bsmsg.New()
	msg.AddBlock(env.Block)
Jeromy's avatar
Jeromy committed
63
	err := pm.network.SendMessage(ctx, env.Peer, msg)
64 65 66 67 68
	if err != nil {
		log.Error(err)
	}
}

Jeromy's avatar
Jeromy committed
69
func (pm *PeerManager) startPeerHandler(ctx context.Context, p peer.ID) *msgQueue {
70 71 72
	_, ok := pm.peers[p]
	if ok {
		// TODO: log an error?
Jeromy's avatar
Jeromy committed
73
		return nil
74 75 76 77 78 79 80 81
	}

	mq := new(msgQueue)
	mq.done = make(chan struct{})
	mq.work = make(chan struct{}, 1)
	mq.p = p

	pm.peers[p] = mq
Jeromy's avatar
Jeromy committed
82 83
	go pm.runQueue(ctx, mq)
	return mq
84 85 86 87 88 89 90 91 92 93 94 95 96
}

func (pm *PeerManager) stopPeerHandler(p peer.ID) {
	pq, ok := pm.peers[p]
	if !ok {
		// TODO: log error?
		return
	}

	close(pq.done)
	delete(pm.peers, p)
}

Jeromy's avatar
Jeromy committed
97
func (pm *PeerManager) runQueue(ctx context.Context, mq *msgQueue) {
98 99 100 101 102 103
	for {
		select {
		case <-mq.work: // there is work to be done

			// TODO: this might not need to be done every time, figure out
			// a good heuristic
Jeromy's avatar
Jeromy committed
104
			err := pm.network.ConnectTo(ctx, mq.p)
105 106 107 108 109
			if err != nil {
				log.Error(err)
				// TODO: cant connect, what now?
			}

Jeromy's avatar
Jeromy committed
110 111 112 113 114
			// grab outgoin message
			mq.outlk.Lock()
			wlm := mq.out
			mq.out = nil
			mq.outlk.Unlock()
115 116 117

			if wlm != nil && !wlm.Empty() {
				// send wantlist updates
Jeromy's avatar
Jeromy committed
118
				err = pm.network.SendMessage(ctx, mq.p, wlm)
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
				if err != nil {
					log.Error("bitswap send error: ", err)
					// TODO: what do we do if this fails?
				}
			}
		case <-mq.done:
			return
		}
	}
}

func (pm *PeerManager) Send(to peer.ID, msg bsmsg.BitSwapMessage) {
	if len(msg.Blocks()) > 0 {
		panic("no blocks here!")
	}
	pm.incoming <- &msgPair{to: to, msg: msg}
}

func (pm *PeerManager) Broadcast(msg bsmsg.BitSwapMessage) {
	pm.incoming <- &msgPair{msg: msg}
}

func (pm *PeerManager) Connected(p peer.ID) {
	pm.connect <- p
}

func (pm *PeerManager) Disconnected(p peer.ID) {
	pm.disconnect <- p
}

// TODO: use goprocess here once i trust it
func (pm *PeerManager) Run(ctx context.Context) {
	for {
		select {
		case msgp := <-pm.incoming:

			// Broadcast message to all if recipient not set
			if msgp.to == "" {
				for _, p := range pm.peers {
					p.addMessage(msgp.msg)
				}
				continue
			}

			p, ok := pm.peers[msgp.to]
			if !ok {
				//TODO: decide, drop message? or dial?
Jeromy's avatar
Jeromy committed
166
				p = pm.startPeerHandler(ctx, msgp.to)
167 168 169 170
			}

			p.addMessage(msgp.msg)
		case p := <-pm.connect:
Jeromy's avatar
Jeromy committed
171
			pm.startPeerHandler(ctx, p)
172 173 174 175 176 177 178 179 180
		case p := <-pm.disconnect:
			pm.stopPeerHandler(p)
		case <-ctx.Done():
			return
		}
	}
}

func (mq *msgQueue) addMessage(msg bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
181
	mq.outlk.Lock()
182
	defer func() {
Jeromy's avatar
Jeromy committed
183
		mq.outlk.Unlock()
184 185 186 187 188 189
		select {
		case mq.work <- struct{}{}:
		default:
		}
	}()

Jeromy's avatar
Jeromy committed
190 191 192 193
	// if we have no message held, or the one we are given is full
	// overwrite the one we are holding
	if mq.out == nil || msg.Full() {
		mq.out = msg
194 195 196 197
		return
	}

	// TODO: add a msg.Combine(...) method
Jeromy's avatar
Jeromy committed
198 199
	// otherwise, combine the one we are holding with the
	// one passed in
200 201
	for _, e := range msg.Wantlist() {
		if e.Cancel {
Jeromy's avatar
Jeromy committed
202
			mq.out.Cancel(e.Key)
203
		} else {
Jeromy's avatar
Jeromy committed
204
			mq.out.AddEntry(e.Key, e.Priority)
205 206 207
		}
	}
}