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

import (
4
	"context"
dirkmc's avatar
dirkmc committed
5
	"fmt"
6

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

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

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

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

29
	if bs.provideEnabled {
30 31 32 33 34 35 36 37 38 39
		// 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)
	}
40 41
}

42
func (bs *Bitswap) taskWorker(ctx context.Context, id int) {
Jeromy's avatar
Jeromy committed
43
	defer log.Debug("bitswap task worker shutting down...")
44
	log := log.With("ID", id)
45
	for {
46
		log.Debug("Bitswap.TaskWorker.Loop")
47 48 49 50 51 52 53
		select {
		case nextEnvelope := <-bs.engine.Outbox():
			select {
			case envelope, ok := <-nextEnvelope:
				if !ok {
					continue
				}
dirkmc's avatar
dirkmc committed
54

55 56 57
				// update the BS ledger to reflect sent message
				// TODO: Should only track *useful* messages in ledger
				outgoing := bsmsg.New(false)
58
				for _, block := range envelope.Message.Blocks() {
59 60 61 62
					log.Debugw("Bitswap.TaskWorker.Work",
						"Target", envelope.Peer,
						"Block", block.Cid(),
					)
63 64
					outgoing.AddBlock(block)
				}
dirkmc's avatar
dirkmc committed
65 66 67 68
				for _, blockPresence := range envelope.Message.BlockPresences() {
					outgoing.AddBlockPresence(blockPresence.Cid, blockPresence.Type)
				}
				// TODO: Only record message as sent if there was no error?
69 70
				bs.engine.MessageSent(envelope.Peer, outgoing)

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

87 88 89 90 91 92 93
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)
dirkmc's avatar
dirkmc committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

	for _, blockPresence := range env.Message.BlockPresences() {
		c := blockPresence.Cid
		switch blockPresence.Type {
		case pb.Message_Have:
			log.Infof("Sending HAVE %s to %s", c.String()[2:8], env.Peer)
		case pb.Message_DontHave:
			log.Infof("Sending DONT_HAVE %s to %s", c.String()[2:8], env.Peer)
		default:
			panic(fmt.Sprintf("unrecognized BlockPresence type %v", blockPresence.Type))
		}

		msgSize += bsmsg.BlockPresenceSize(c)
		msg.AddBlockPresence(c, blockPresence.Type)
	}
109 110 111 112 113 114 115 116 117
	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 {
dirkmc's avatar
dirkmc committed
118 119
		// log.Infof("sendblock error: %s", err)
		log.Errorf("SendMessage error: %s. size: %d. block-presence length: %d", err, msg.Size(), len(env.Message.BlockPresences()))
120
	}
dirkmc's avatar
dirkmc committed
121
	log.Infof("Sent message to %s", env.Peer)
122 123
}

124
func (bs *Bitswap) provideWorker(px process.Process) {
125 126 127 128 129 130 131 132 133
	// 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()
134

135
	limit := make(chan struct{}, provideWorkerMax)
136

137
	limitedGoProvide := func(k cid.Cid, wid int) {
138 139 140 141
		defer func() {
			// replace token when done
			<-limit
		}()
142

143 144
		log.Debugw("Bitswap.ProvideWorker.Start", "ID", wid, "cid", k)
		defer log.Debugw("Bitswap.ProvideWorker.End", "ID", wid, "cid", k)
145

146 147
		ctx, cancel := context.WithTimeout(ctx, provideTimeout) // timeout ctx
		defer cancel()
148

149
		if err := bs.network.Provide(ctx, k); err != nil {
150
			log.Warn(err)
151
		}
152
	}
153 154 155

	// worker spawner, reads from bs.provideKeys until it closes, spawning a
	// _ratelimited_ number of workers to handle each key.
156
	for wid := 2; ; wid++ {
157
		log.Debug("Bitswap.ProvideWorker.Loop")
158

159 160 161 162 163 164 165 166
		select {
		case <-px.Closing():
			return
		case k, ok := <-bs.provideKeys:
			if !ok {
				log.Debug("provideKeys channel closed")
				return
			}
167 168 169
			select {
			case <-px.Closing():
				return
170 171
			case limit <- struct{}{}:
				go limitedGoProvide(k, wid)
172 173
			}
		}
174
	}
175 176
}

177 178
func (bs *Bitswap) provideCollector(ctx context.Context) {
	defer close(bs.provideKeys)
179 180 181
	var toProvide []cid.Cid
	var nextKey cid.Cid
	var keysOut chan cid.Cid
182 183 184

	for {
		select {
185
		case blkey, ok := <-bs.newBlocks:
186 187 188 189
			if !ok {
				log.Debug("newBlocks channel closed")
				return
			}
190

Jeromy's avatar
Jeromy committed
191
			if keysOut == nil {
192
				nextKey = blkey
Jeromy's avatar
Jeromy committed
193 194
				keysOut = bs.provideKeys
			} else {
195
				toProvide = append(toProvide, blkey)
Jeromy's avatar
Jeromy committed
196 197
			}
		case keysOut <- nextKey:
Jeromy's avatar
Jeromy committed
198 199 200
			if len(toProvide) > 0 {
				nextKey = toProvide[0]
				toProvide = toProvide[1:]
201
			} else {
Jeromy's avatar
Jeromy committed
202
				keysOut = nil
203 204 205 206 207 208
			}
		case <-ctx.Done():
			return
		}
	}
}