workers.go 4.23 KB
Newer Older
1 2 3 4 5
package bitswap

import (
	"time"

6 7 8 9
	inflect "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/chuckpreslar/inflect"
	process "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	u "github.com/ipfs/go-ipfs/util"
10 11
)

12
func (bs *Bitswap) startWorkers(px process.Process, ctx context.Context) {
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
	// Start up a worker to handle block requests this node is making
	px.Go(func(px process.Process) {
		bs.clientWorker(ctx)
	})

	// Start up a worker to handle requests from other nodes for the data on this node
	px.Go(func(px process.Process) {
		bs.taskWorker(ctx)
	})

	// Start up a worker to manage periodically resending our wantlist out to peers
	px.Go(func(px process.Process) {
		bs.rebroadcastWorker(ctx)
	})

28 29 30 31
	px.Go(func(px process.Process) {
		bs.provideCollector(ctx)
	})

32 33 34 35 36
	// Spawn up multiple workers to handle incoming blocks
	// consider increasing number if providing blocks bottlenecks
	// file transfers
	for i := 0; i < provideWorkers; i++ {
		px.Go(func(px process.Process) {
Jeromy's avatar
Jeromy committed
37
			bs.provideWorker(ctx)
38 39 40 41
		})
	}
}

42
func (bs *Bitswap) taskWorker(ctx context.Context) {
43 44 45 46 47 48 49 50 51 52 53
	defer log.Info("bitswap task worker shutting down...")
	for {
		select {
		case nextEnvelope := <-bs.engine.Outbox():
			select {
			case envelope, ok := <-nextEnvelope:
				if !ok {
					continue
				}
				log.Event(ctx, "deliverBlocks", envelope.Message, envelope.Peer)
				bs.send(ctx, envelope.Peer, envelope.Message)
Jeromy's avatar
Jeromy committed
54
				envelope.Sent()
55 56 57 58 59 60 61 62 63
			case <-ctx.Done():
				return
			}
		case <-ctx.Done():
			return
		}
	}
}

64
func (bs *Bitswap) provideWorker(ctx context.Context) {
65 66
	for {
		select {
67
		case k, ok := <-bs.provideKeys:
68
			if !ok {
69
				log.Debug("provideKeys channel closed")
70 71
				return
			}
Henry's avatar
Henry committed
72
			ctx, cancel := context.WithTimeout(ctx, provideTimeout)
73
			err := bs.network.Provide(ctx, k)
74 75 76
			if err != nil {
				log.Error(err)
			}
Henry's avatar
Henry committed
77
			cancel()
78 79 80 81 82 83
		case <-ctx.Done():
			return
		}
	}
}

84 85
func (bs *Bitswap) provideCollector(ctx context.Context) {
	defer close(bs.provideKeys)
Jeromy's avatar
Jeromy committed
86
	var toProvide []u.Key
87
	var nextKey u.Key
Jeromy's avatar
Jeromy committed
88
	var keysOut chan u.Key
89 90 91 92 93 94 95 96

	for {
		select {
		case blk, ok := <-bs.newBlocks:
			if !ok {
				log.Debug("newBlocks channel closed")
				return
			}
Jeromy's avatar
Jeromy committed
97 98 99 100
			if keysOut == nil {
				nextKey = blk.Key()
				keysOut = bs.provideKeys
			} else {
Jeromy's avatar
Jeromy committed
101
				toProvide = append(toProvide, blk.Key())
Jeromy's avatar
Jeromy committed
102 103
			}
		case keysOut <- nextKey:
Jeromy's avatar
Jeromy committed
104 105 106
			if len(toProvide) > 0 {
				nextKey = toProvide[0]
				toProvide = toProvide[1:]
107
			} else {
Jeromy's avatar
Jeromy committed
108
				keysOut = nil
109 110 111 112 113 114 115
			}
		case <-ctx.Done():
			return
		}
	}
}

116
// TODO ensure only one active request per key
117
func (bs *Bitswap) clientWorker(parent context.Context) {
118 119 120 121 122 123 124 125 126 127 128 129 130 131
	defer log.Info("bitswap client worker shutting down...")

	for {
		select {
		case req := <-bs.batchRequests:
			keys := req.keys
			if len(keys) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
			for i, k := range keys {
				bs.wantlist.Add(k, kMaxPriority-i)
			}

132 133 134 135 136
			done := make(chan struct{})
			go func() {
				bs.wantNewBlocks(req.ctx, keys)
				close(done)
			}()
137 138 139 140

			// NB: Optimization. Assumes that providers of key[0] are likely to
			// be able to provide for all keys. This currently holds true in most
			// every situation. Later, this assumption may not hold as true.
Henry's avatar
Henry committed
141
			child, cancel := context.WithTimeout(req.ctx, providerRequestTimeout)
142 143 144 145 146
			providers := bs.network.FindProvidersAsync(child, keys[0], maxProvidersPerRequest)
			err := bs.sendWantlistToPeers(req.ctx, providers)
			if err != nil {
				log.Debugf("error sending wantlist: %s", err)
			}
Henry's avatar
Henry committed
147
			cancel()
148 149 150 151

			// Wait for wantNewBlocks to finish
			<-done

152 153 154 155 156 157
		case <-parent.Done():
			return
		}
	}
}

158
func (bs *Bitswap) rebroadcastWorker(parent context.Context) {
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	ctx, cancel := context.WithCancel(parent)
	defer cancel()

	broadcastSignal := time.After(rebroadcastDelay.Get())

	for {
		select {
		case <-time.Tick(10 * time.Second):
			n := bs.wantlist.Len()
			if n > 0 {
				log.Debug(n, inflect.FromNumber("keys", n), "in bitswap wantlist")
			}
		case <-broadcastSignal: // resend unfulfilled wantlist keys
			entries := bs.wantlist.Entries()
			if len(entries) > 0 {
				bs.sendWantlistToProviders(ctx, entries)
			}
			broadcastSignal = time.After(rebroadcastDelay.Get())
		case <-parent.Done():
			return
		}
	}
}