session.go 7.85 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4
package bitswap

import (
	"context"
5
	"fmt"
Jeromy's avatar
Jeromy committed
6 7 8 9
	"time"

	notifications "github.com/ipfs/go-ipfs/exchange/bitswap/notifications"

10 11
	cid "gx/ipfs/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ/go-cid"
	blocks "gx/ipfs/QmSn9Td7xgxm9EV7iEjTckpUWmWApggzPxu7eFGWkkpwin/go-block-format"
Jeromy's avatar
Jeromy committed
12
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
13
	loggables "gx/ipfs/QmT4PgCNdv73hnFAqzHqwW44q7M9PWpykSswHDxndquZbc/go-libp2p-loggables"
Jeromy's avatar
Jeromy committed
14
	lru "gx/ipfs/QmVYxfoJQiZijTgPNHCHgHELvQpbsJNTg6Crmc3dQkj3yy/golang-lru"
15
	peer "gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
16 17 18 19
)

const activeWantsLimit = 16

Jeromy's avatar
Jeromy committed
20 21 22
// Session holds state for an individual bitswap transfer operation.
// This allows bitswap to make smarter decisions about who to send wantlist
// info to, and who to request blocks from
Jeromy's avatar
Jeromy committed
23 24
type Session struct {
	ctx            context.Context
25
	tofetch        *cidQueue
Jeromy's avatar
Jeromy committed
26 27 28
	activePeers    map[peer.ID]struct{}
	activePeersArr []peer.ID

Jeromy's avatar
Jeromy committed
29 30 31 32 33
	bs           *Bitswap
	incoming     chan blkRecv
	newReqs      chan []*cid.Cid
	cancelKeys   chan []*cid.Cid
	interestReqs chan interestReq
Jeromy's avatar
Jeromy committed
34 35 36 37 38 39 40 41 42 43 44 45 46

	interest  *lru.Cache
	liveWants map[string]time.Time

	tick          *time.Timer
	baseTickDelay time.Duration

	latTotal time.Duration
	fetchcnt int

	notif notifications.PubSub

	uuid logging.Loggable
Jeromy's avatar
Jeromy committed
47

48 49
	id  uint64
	tag string
Jeromy's avatar
Jeromy committed
50 51
}

Jeromy's avatar
Jeromy committed
52 53
// NewSession creates a new bitswap session whose lifetime is bounded by the
// given context
Jeromy's avatar
Jeromy committed
54 55 56 57 58 59
func (bs *Bitswap) NewSession(ctx context.Context) *Session {
	s := &Session{
		activePeers:   make(map[peer.ID]struct{}),
		liveWants:     make(map[string]time.Time),
		newReqs:       make(chan []*cid.Cid),
		cancelKeys:    make(chan []*cid.Cid),
60
		tofetch:       newCidQueue(),
Jeromy's avatar
Jeromy committed
61
		interestReqs:  make(chan interestReq),
Jeromy's avatar
Jeromy committed
62 63 64 65 66 67
		ctx:           ctx,
		bs:            bs,
		incoming:      make(chan blkRecv),
		notif:         notifications.New(),
		uuid:          loggables.Uuid("GetBlockRequest"),
		baseTickDelay: time.Millisecond * 500,
Jeromy's avatar
Jeromy committed
68
		id:            bs.getNextSessionID(),
Jeromy's avatar
Jeromy committed
69 70
	}

71 72
	s.tag = fmt.Sprint("bs-ses-", s.id)

Jeromy's avatar
Jeromy committed
73 74 75 76 77 78 79 80 81 82 83 84
	cache, _ := lru.New(2048)
	s.interest = cache

	bs.sessLk.Lock()
	bs.sessions = append(bs.sessions, s)
	bs.sessLk.Unlock()

	go s.run(ctx)

	return s
}

Jeromy's avatar
Jeromy committed
85 86 87 88 89 90 91 92 93 94 95 96
func (bs *Bitswap) removeSession(s *Session) {
	bs.sessLk.Lock()
	defer bs.sessLk.Unlock()
	for i := 0; i < len(bs.sessions); i++ {
		if bs.sessions[i] == s {
			bs.sessions[i] = bs.sessions[len(bs.sessions)-1]
			bs.sessions = bs.sessions[:len(bs.sessions)-1]
			return
		}
	}
}

Jeromy's avatar
Jeromy committed
97 98 99 100 101
type blkRecv struct {
	from peer.ID
	blk  blocks.Block
}

Jeromy's avatar
Jeromy committed
102
func (s *Session) receiveBlockFrom(from peer.ID, blk blocks.Block) {
Jeromy's avatar
Jeromy committed
103 104 105 106
	select {
	case s.incoming <- blkRecv{from: from, blk: blk}:
	case <-s.ctx.Done():
	}
Jeromy's avatar
Jeromy committed
107 108
}

Jeromy's avatar
Jeromy committed
109 110 111 112 113 114 115 116 117 118 119 120 121
type interestReq struct {
	c    *cid.Cid
	resp chan bool
}

// TODO: PERF: this is using a channel to guard a map access against race
// conditions. This is definitely much slower than a mutex, though its unclear
// if it will actually induce any noticeable slowness. This is implemented this
// way to avoid adding a more complex set of mutexes around the liveWants map.
// note that in the average case (where this session *is* interested in the
// block we received) this function will not be called, as the cid will likely
// still be in the interest cache.
func (s *Session) isLiveWant(c *cid.Cid) bool {
122
	resp := make(chan bool, 1)
Jeromy's avatar
Jeromy committed
123 124 125 126
	s.interestReqs <- interestReq{
		c:    c,
		resp: resp,
	}
Jeromy's avatar
Jeromy committed
127 128 129 130 131 132 133

	select {
	case want := <-resp:
		return want
	case <-s.ctx.Done():
		return false
	}
Jeromy's avatar
Jeromy committed
134 135
}

Jeromy's avatar
Jeromy committed
136
func (s *Session) interestedIn(c *cid.Cid) bool {
Jeromy's avatar
Jeromy committed
137
	return s.interest.Contains(c.KeyString()) || s.isLiveWant(c)
Jeromy's avatar
Jeromy committed
138 139 140 141 142 143 144 145
}

const provSearchDelay = time.Second * 10

func (s *Session) addActivePeer(p peer.ID) {
	if _, ok := s.activePeers[p]; !ok {
		s.activePeers[p] = struct{}{}
		s.activePeersArr = append(s.activePeersArr, p)
146 147 148

		cmgr := s.bs.network.ConnectionManager()
		cmgr.TagPeer(p, s.tag, 10)
Jeromy's avatar
Jeromy committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
	}
}

func (s *Session) resetTick() {
	if s.latTotal == 0 {
		s.tick.Reset(provSearchDelay)
	} else {
		avLat := s.latTotal / time.Duration(s.fetchcnt)
		s.tick.Reset(s.baseTickDelay + (3 * avLat))
	}
}

func (s *Session) run(ctx context.Context) {
	s.tick = time.NewTimer(provSearchDelay)
	newpeers := make(chan peer.ID, 16)
	for {
		select {
		case blk := <-s.incoming:
			s.tick.Stop()

169 170 171
			if blk.from != "" {
				s.addActivePeer(blk.from)
			}
Jeromy's avatar
Jeromy committed
172 173 174 175 176 177 178 179

			s.receiveBlock(ctx, blk.blk)

			s.resetTick()
		case keys := <-s.newReqs:
			for _, k := range keys {
				s.interest.Add(k.KeyString(), nil)
			}
Jeromy's avatar
Jeromy committed
180 181
			if len(s.liveWants) < activeWantsLimit {
				toadd := activeWantsLimit - len(s.liveWants)
Jeromy's avatar
Jeromy committed
182 183 184 185 186 187 188 189 190
				if toadd > len(keys) {
					toadd = len(keys)
				}

				now := keys[:toadd]
				keys = keys[toadd:]

				s.wantBlocks(ctx, now)
			}
191 192 193
			for _, k := range keys {
				s.tofetch.Push(k)
			}
Jeromy's avatar
Jeromy committed
194 195 196 197 198
		case keys := <-s.cancelKeys:
			s.cancel(keys)

		case <-s.tick.C:
			var live []*cid.Cid
Jeromy's avatar
Jeromy committed
199
			for c := range s.liveWants {
Jeromy's avatar
Jeromy committed
200 201 202 203 204 205
				cs, _ := cid.Cast([]byte(c))
				live = append(live, cs)
				s.liveWants[c] = time.Now()
			}

			// Broadcast these keys to everyone we're connected to
Jeromy's avatar
Jeromy committed
206
			s.bs.wm.WantBlocks(ctx, live, nil, s.id)
Jeromy's avatar
Jeromy committed
207 208

			if len(live) > 0 {
Jeromy's avatar
Jeromy committed
209 210 211 212 213 214 215
				go func(k *cid.Cid) {
					// TODO: have a task queue setup for this to:
					// - rate limit
					// - manage timeouts
					// - ensure two 'findprovs' calls for the same block don't run concurrently
					// - share peers between sessions based on interest set
					for p := range s.bs.network.FindProvidersAsync(ctx, k, 10) {
Jeromy's avatar
Jeromy committed
216 217
						newpeers <- p
					}
Jeromy's avatar
Jeromy committed
218
				}(live[0])
Jeromy's avatar
Jeromy committed
219 220 221 222
			}
			s.resetTick()
		case p := <-newpeers:
			s.addActivePeer(p)
Jeromy's avatar
Jeromy committed
223
		case lwchk := <-s.interestReqs:
224
			lwchk.resp <- s.cidIsWanted(lwchk.c)
Jeromy's avatar
Jeromy committed
225
		case <-ctx.Done():
Jeromy's avatar
Jeromy committed
226
			s.tick.Stop()
Jeromy's avatar
Jeromy committed
227
			s.bs.removeSession(s)
228 229 230 231 232

			cmgr := s.bs.network.ConnectionManager()
			for _, p := range s.activePeersArr {
				cmgr.UntagPeer(p, s.tag)
			}
Jeromy's avatar
Jeromy committed
233 234 235 236 237
			return
		}
	}
}

238 239 240 241 242 243 244 245 246
func (s *Session) cidIsWanted(c *cid.Cid) bool {
	_, ok := s.liveWants[c.KeyString()]
	if !ok {
		ok = s.tofetch.Has(c)
	}

	return ok
}

Jeromy's avatar
Jeromy committed
247
func (s *Session) receiveBlock(ctx context.Context, blk blocks.Block) {
248 249 250 251 252 253 254 255 256 257
	c := blk.Cid()
	if s.cidIsWanted(c) {
		ks := c.KeyString()
		tval, ok := s.liveWants[ks]
		if ok {
			s.latTotal += time.Since(tval)
			delete(s.liveWants, ks)
		} else {
			s.tofetch.Remove(c)
		}
Jeromy's avatar
Jeromy committed
258 259 260
		s.fetchcnt++
		s.notif.Publish(blk)

261 262
		if next := s.tofetch.Pop(); next != nil {
			s.wantBlocks(ctx, []*cid.Cid{next})
Jeromy's avatar
Jeromy committed
263 264 265 266 267 268 269 270
		}
	}
}

func (s *Session) wantBlocks(ctx context.Context, ks []*cid.Cid) {
	for _, c := range ks {
		s.liveWants[c.KeyString()] = time.Now()
	}
Jeromy's avatar
Jeromy committed
271
	s.bs.wm.WantBlocks(ctx, ks, s.activePeersArr, s.id)
Jeromy's avatar
Jeromy committed
272 273 274 275
}

func (s *Session) cancel(keys []*cid.Cid) {
	for _, c := range keys {
276
		s.tofetch.Remove(c)
Jeromy's avatar
Jeromy committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290
	}
}

func (s *Session) cancelWants(keys []*cid.Cid) {
	s.cancelKeys <- keys
}

func (s *Session) fetch(ctx context.Context, keys []*cid.Cid) {
	select {
	case s.newReqs <- keys:
	case <-ctx.Done():
	}
}

Jeromy's avatar
Jeromy committed
291 292 293
// GetBlocks fetches a set of blocks within the context of this session and
// returns a channel that found blocks will be returned on. No order is
// guaranteed on the returned blocks.
Jeromy's avatar
Jeromy committed
294 295 296 297 298
func (s *Session) GetBlocks(ctx context.Context, keys []*cid.Cid) (<-chan blocks.Block, error) {
	ctx = logging.ContextWithLoggable(ctx, s.uuid)
	return getBlocksImpl(ctx, keys, s.notif, s.fetch, s.cancelWants)
}

Jeromy's avatar
Jeromy committed
299
// GetBlock fetches a single block
Jeromy's avatar
Jeromy committed
300 301 302
func (s *Session) GetBlock(parent context.Context, k *cid.Cid) (blocks.Block, error) {
	return getBlock(parent, k, s.GetBlocks)
}
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

type cidQueue struct {
	elems []*cid.Cid
	eset  *cid.Set
}

func newCidQueue() *cidQueue {
	return &cidQueue{eset: cid.NewSet()}
}

func (cq *cidQueue) Pop() *cid.Cid {
	for {
		if len(cq.elems) == 0 {
			return nil
		}

		out := cq.elems[0]
		cq.elems = cq.elems[1:]

		if cq.eset.Has(out) {
			cq.eset.Remove(out)
			return out
		}
	}
}

func (cq *cidQueue) Push(c *cid.Cid) {
	if cq.eset.Visit(c) {
		cq.elems = append(cq.elems, c)
	}
}

func (cq *cidQueue) Remove(c *cid.Cid) {
	cq.eset.Remove(c)
}

func (cq *cidQueue) Has(c *cid.Cid) bool {
	return cq.eset.Has(c)
}

func (cq *cidQueue) Len() int {
	return cq.eset.Len()
}