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

import (
4
	"context"
5

6
	engine "github.com/ipfs/go-bitswap/decision"
Jeromy's avatar
Jeromy committed
7 8 9 10 11
	bsmsg "github.com/ipfs/go-bitswap/message"
	cid "github.com/ipfs/go-cid"
	logging "github.com/ipfs/go-log"
	process "github.com/jbenet/goprocess"
	procctx "github.com/jbenet/goprocess/context"
12 13
)

14 15
// TaskWorkerCount is the total number of simultaneous threads sending
// outgoing messages
16
var TaskWorkerCount = 8
17

18
func (bs *Bitswap) startWorkers(ctx context.Context, px process.Process) {
19

Jeromy's avatar
Jeromy committed
20 21
	// Start up workers to handle requests from other nodes for the data on this node
	for i := 0; i < TaskWorkerCount; i++ {
22
		i := i
Jeromy's avatar
Jeromy committed
23
		px.Go(func(px process.Process) {
24
			bs.taskWorker(ctx, i)
Jeromy's avatar
Jeromy committed
25 26
		})
	}
27

28 29 30 31 32 33 34 35 36 37 38
	if ProvideEnabled {
		// Start up a worker to manage sending out provides messages
		px.Go(func(px process.Process) {
			bs.provideCollector(ctx)
		})

		// Spawn up multiple workers to handle incoming blocks
		// consider increasing number if providing blocks bottlenecks
		// file transfers
		px.Go(bs.provideWorker)
	}
39 40
}

41
func (bs *Bitswap) taskWorker(ctx context.Context, id int) {
Jeromy's avatar
Jeromy committed
42
	idmap := logging.LoggableMap{"ID": id}
Jeromy's avatar
Jeromy committed
43
	defer log.Debug("bitswap task worker shutting down...")
44
	for {
45
		log.Event(ctx, "Bitswap.TaskWorker.Loop", idmap)
46 47 48 49 50 51 52
		select {
		case nextEnvelope := <-bs.engine.Outbox():
			select {
			case envelope, ok := <-nextEnvelope:
				if !ok {
					continue
				}
53 54 55
				// update the BS ledger to reflect sent message
				// TODO: Should only track *useful* messages in ledger
				outgoing := bsmsg.New(false)
56 57 58 59 60 61 62 63 64 65
				for _, block := range envelope.Message.Blocks() {
					log.Event(ctx, "Bitswap.TaskWorker.Work", logging.LoggableF(func() map[string]interface{} {
						return logging.LoggableMap{
							"ID":     id,
							"Target": envelope.Peer.Pretty(),
							"Block":  block.Cid().String(),
						}
					}))
					outgoing.AddBlock(block)
				}
66 67
				bs.engine.MessageSent(envelope.Peer, outgoing)

68
				bs.sendBlocks(ctx, envelope)
Jeromy's avatar
Jeromy committed
69
				bs.counterLk.Lock()
70 71 72 73
				for _, block := range envelope.Message.Blocks() {
					bs.counters.blocksSent++
					bs.counters.dataSent += uint64(len(block.RawData()))
				}
Jeromy's avatar
Jeromy committed
74
				bs.counterLk.Unlock()
75 76 77 78 79 80 81 82 83
			case <-ctx.Done():
				return
			}
		case <-ctx.Done():
			return
		}
	}
}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
func (bs *Bitswap) sendBlocks(ctx context.Context, env *engine.Envelope) {
	// Blocks need to be sent synchronously to maintain proper backpressure
	// throughout the network stack
	defer env.Sent()

	msgSize := 0
	msg := bsmsg.New(false)
	for _, block := range env.Message.Blocks() {
		msgSize += len(block.RawData())
		msg.AddBlock(block)
		log.Infof("Sending block %s to %s", block, env.Peer)
	}

	bs.sentHistogram.Observe(float64(msgSize))
	err := bs.network.SendMessage(ctx, env.Peer, msg)
	if err != nil {
		log.Infof("sendblock error: %s", err)
	}
}

104
func (bs *Bitswap) provideWorker(px process.Process) {
105 106 107 108 109 110 111 112 113
	// FIXME: OnClosingContext returns a _custom_ context type.
	// Unfortunately, deriving a new cancelable context from this custom
	// type fires off a goroutine. To work around this, we create a single
	// cancelable context up-front and derive all sub-contexts from that.
	//
	// See: https://github.com/ipfs/go-ipfs/issues/5810
	ctx := procctx.OnClosingContext(px)
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
114

115
	limit := make(chan struct{}, provideWorkerMax)
116

117
	limitedGoProvide := func(k cid.Cid, wid int) {
118 119 120 121
		defer func() {
			// replace token when done
			<-limit
		}()
Jeromy's avatar
Jeromy committed
122
		ev := logging.LoggableMap{"ID": wid}
123

124
		defer log.EventBegin(ctx, "Bitswap.ProvideWorker.Work", ev, k).Done()
125

126 127
		ctx, cancel := context.WithTimeout(ctx, provideTimeout) // timeout ctx
		defer cancel()
128

129
		if err := bs.network.Provide(ctx, k); err != nil {
Jeromy's avatar
Jeromy committed
130
			log.Warning(err)
131
		}
132
	}
133 134 135

	// worker spawner, reads from bs.provideKeys until it closes, spawning a
	// _ratelimited_ number of workers to handle each key.
136 137
	for wid := 2; ; wid++ {
		ev := logging.LoggableMap{"ID": 1}
138
		log.Event(ctx, "Bitswap.ProvideWorker.Loop", ev)
139

140 141 142 143 144 145 146 147
		select {
		case <-px.Closing():
			return
		case k, ok := <-bs.provideKeys:
			if !ok {
				log.Debug("provideKeys channel closed")
				return
			}
148 149 150
			select {
			case <-px.Closing():
				return
151 152
			case limit <- struct{}{}:
				go limitedGoProvide(k, wid)
153 154
			}
		}
155
	}
156 157
}

158 159
func (bs *Bitswap) provideCollector(ctx context.Context) {
	defer close(bs.provideKeys)
160 161 162
	var toProvide []cid.Cid
	var nextKey cid.Cid
	var keysOut chan cid.Cid
163 164 165

	for {
		select {
166
		case blkey, ok := <-bs.newBlocks:
167 168 169 170
			if !ok {
				log.Debug("newBlocks channel closed")
				return
			}
171

Jeromy's avatar
Jeromy committed
172
			if keysOut == nil {
173
				nextKey = blkey
Jeromy's avatar
Jeromy committed
174 175
				keysOut = bs.provideKeys
			} else {
176
				toProvide = append(toProvide, blkey)
Jeromy's avatar
Jeromy committed
177 178
			}
		case keysOut <- nextKey:
Jeromy's avatar
Jeromy committed
179 180 181
			if len(toProvide) > 0 {
				nextKey = toProvide[0]
				toProvide = toProvide[1:]
182
			} else {
Jeromy's avatar
Jeromy committed
183
				keysOut = nil
184 185 186 187 188 189
			}
		case <-ctx.Done():
			return
		}
	}
}