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

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

8 9
	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"
10
	key "github.com/ipfs/go-ipfs/blocks/key"
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
	// Start up a worker to handle block requests this node is making
	px.Go(func(px process.Process) {
Jeromy's avatar
Jeromy committed
34
		bs.providerConnector(ctx)
35 36
	})

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

	// Start up a worker to manage periodically resending our wantlist out to peers
Jeromy's avatar
Jeromy committed
45 46 47
	px.Go(func(px process.Process) {
		bs.rebroadcastWorker(ctx)
	})
48

Jeromy's avatar
Jeromy committed
49
	// Start up a worker to manage sending out provides messages
50 51 52 53
	px.Go(func(px process.Process) {
		bs.provideCollector(ctx)
	})

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

64
func (bs *Bitswap) taskWorker(ctx context.Context) {
65 66 67 68 69 70 71 72 73
	defer log.Info("bitswap task worker shutting down...")
	for {
		select {
		case nextEnvelope := <-bs.engine.Outbox():
			select {
			case envelope, ok := <-nextEnvelope:
				if !ok {
					continue
				}
74

75
				bs.wm.SendBlock(ctx, envelope)
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)
107 108 109
	var toProvide []key.Key
	var nextKey key.Key
	var keysOut chan key.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
		}
	}
}

Jeromy's avatar
Jeromy committed
137 138
// connects to providers for the given keys
func (bs *Bitswap) providerConnector(parent context.Context) {
139 140 141 142
	defer log.Info("bitswap client worker shutting down...")

	for {
		select {
Jeromy's avatar
Jeromy committed
143
		case req := <-bs.findKeys:
144 145 146 147 148 149 150 151 152
			keys := req.keys
			if len(keys) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}

			// 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
153
			child, cancel := context.WithTimeout(req.ctx, providerRequestTimeout)
154
			providers := bs.network.FindProvidersAsync(child, keys[0], maxProvidersPerRequest)
155 156
			for p := range providers {
				go bs.network.ConnectTo(req.ctx, p)
157
			}
Henry's avatar
Henry committed
158
			cancel()
159

160 161 162 163 164 165
		case <-parent.Done():
			return
		}
	}
}

166
func (bs *Bitswap) rebroadcastWorker(parent context.Context) {
167 168 169
	ctx, cancel := context.WithCancel(parent)
	defer cancel()

170 171 172 173 174
	broadcastSignal := time.NewTicker(rebroadcastDelay.Get())
	defer broadcastSignal.Stop()

	tick := time.NewTicker(10 * time.Second)
	defer tick.Stop()
175 176 177

	for {
		select {
178 179
		case <-tick.C:
			n := bs.wm.wl.Len()
180
			if n > 0 {
Jeromy's avatar
Jeromy committed
181
				log.Debug(n, "keys in bitswap wantlist")
182
			}
183 184
		case <-broadcastSignal.C: // resend unfulfilled wantlist keys
			entries := bs.wm.wl.Entries()
185
			if len(entries) > 0 {
186
				bs.connectToProviders(ctx, entries)
187 188 189 190 191 192
			}
		case <-parent.Done():
			return
		}
	}
}