workers.go 4.49 KB
Newer Older
1 2 3
package bitswap

import (
4 5
	"os"
	"strconv"
6 7
	"time"

8 9 10
	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"
11 12
)

13
var TaskWorkerCount = 8
14 15

func init() {
Jeromy Johnson's avatar
Jeromy Johnson committed
16
	twc := os.Getenv("IPFS_BITSWAP_TASK_WORKERS")
17 18 19
	if twc != "" {
		n, err := strconv.Atoi(twc)
		if err != nil {
Jeromy's avatar
Jeromy committed
20
			log.Error(err)
21 22
			return
		}
Jeromy's avatar
Jeromy committed
23 24 25
		if n > 0 {
			TaskWorkerCount = n
		} else {
Jeromy Johnson's avatar
Jeromy Johnson committed
26
			log.Errorf("Invalid value of '%d' for IPFS_BITSWAP_TASK_WORKERS", n)
Jeromy's avatar
Jeromy committed
27
		}
28 29
	}
}
Jeromy's avatar
Jeromy committed
30

31
func (bs *Bitswap) startWorkers(px process.Process, ctx context.Context) {
32 33 34 35 36
	// Start up a worker to handle block requests this node is making
	px.Go(func(px process.Process) {
		bs.clientWorker(ctx)
	})

Jeromy's avatar
Jeromy committed
37 38 39 40 41 42
	// Start up workers to handle requests from other nodes for the data on this node
	for i := 0; i < TaskWorkerCount; i++ {
		px.Go(func(px process.Process) {
			bs.taskWorker(ctx)
		})
	}
43 44 45 46 47 48

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

49 50 51 52
	px.Go(func(px process.Process) {
		bs.provideCollector(ctx)
	})

53 54 55 56 57
	// 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
58
			bs.provideWorker(ctx)
59 60 61 62
		})
	}
}

63
func (bs *Bitswap) taskWorker(ctx context.Context) {
64 65 66 67 68 69 70 71 72 73 74
	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
75
				envelope.Sent()
76 77 78 79 80 81 82 83 84
			case <-ctx.Done():
				return
			}
		case <-ctx.Done():
			return
		}
	}
}

85
func (bs *Bitswap) provideWorker(ctx context.Context) {
86 87
	for {
		select {
88
		case k, ok := <-bs.provideKeys:
89
			if !ok {
90
				log.Debug("provideKeys channel closed")
91 92
				return
			}
Henry's avatar
Henry committed
93
			ctx, cancel := context.WithTimeout(ctx, provideTimeout)
94
			err := bs.network.Provide(ctx, k)
95 96 97
			if err != nil {
				log.Error(err)
			}
Henry's avatar
Henry committed
98
			cancel()
99 100 101 102 103 104
		case <-ctx.Done():
			return
		}
	}
}

105 106
func (bs *Bitswap) provideCollector(ctx context.Context) {
	defer close(bs.provideKeys)
Jeromy's avatar
Jeromy committed
107
	var toProvide []u.Key
108
	var nextKey u.Key
Jeromy's avatar
Jeromy committed
109
	var keysOut chan u.Key
110 111 112 113 114 115 116 117

	for {
		select {
		case blk, ok := <-bs.newBlocks:
			if !ok {
				log.Debug("newBlocks channel closed")
				return
			}
Jeromy's avatar
Jeromy committed
118 119 120 121
			if keysOut == nil {
				nextKey = blk.Key()
				keysOut = bs.provideKeys
			} else {
Jeromy's avatar
Jeromy committed
122
				toProvide = append(toProvide, blk.Key())
Jeromy's avatar
Jeromy committed
123 124
			}
		case keysOut <- nextKey:
Jeromy's avatar
Jeromy committed
125 126 127
			if len(toProvide) > 0 {
				nextKey = toProvide[0]
				toProvide = toProvide[1:]
128
			} else {
Jeromy's avatar
Jeromy committed
129
				keysOut = nil
130 131 132 133 134 135 136
			}
		case <-ctx.Done():
			return
		}
	}
}

137
// TODO ensure only one active request per key
138
func (bs *Bitswap) clientWorker(parent context.Context) {
139 140 141 142 143 144 145 146 147 148 149 150 151 152
	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)
			}

153 154 155 156 157
			done := make(chan struct{})
			go func() {
				bs.wantNewBlocks(req.ctx, keys)
				close(done)
			}()
158 159 160 161

			// 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
162
			child, cancel := context.WithTimeout(req.ctx, providerRequestTimeout)
163 164 165 166 167
			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
168
			cancel()
169 170 171 172

			// Wait for wantNewBlocks to finish
			<-done

173 174 175 176 177 178
		case <-parent.Done():
			return
		}
	}
}

179
func (bs *Bitswap) rebroadcastWorker(parent context.Context) {
180 181 182 183
	ctx, cancel := context.WithCancel(parent)
	defer cancel()

	broadcastSignal := time.After(rebroadcastDelay.Get())
Jeromy's avatar
Jeromy committed
184
	tick := time.Tick(10 * time.Second)
185 186 187

	for {
		select {
Jeromy's avatar
Jeromy committed
188
		case <-tick:
189 190
			n := bs.wantlist.Len()
			if n > 0 {
Jeromy's avatar
Jeromy committed
191
				log.Debug(n, "keys in bitswap wantlist")
192 193 194 195 196 197 198 199 200 201 202 203
			}
		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
		}
	}
}