query.go 7.9 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package dht

import (
Jeromy's avatar
Jeromy committed
4
	"context"
Steven Allen's avatar
Steven Allen committed
5
	"errors"
6 7
	"sync"

8
	logging "github.com/ipfs/go-log"
George Antoniadis's avatar
George Antoniadis committed
9
	todoctr "github.com/ipfs/go-todocounter"
10 11
	process "github.com/jbenet/goprocess"
	ctxproc "github.com/jbenet/goprocess/context"
12
	kb "github.com/libp2p/go-libp2p-kbucket"
Jeromy's avatar
Jeromy committed
13
	inet "github.com/libp2p/go-libp2p-net"
14 15 16 17
	peer "github.com/libp2p/go-libp2p-peer"
	pset "github.com/libp2p/go-libp2p-peer/peerset"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	queue "github.com/libp2p/go-libp2p-peerstore/queue"
George Antoniadis's avatar
George Antoniadis committed
18 19
	routing "github.com/libp2p/go-libp2p-routing"
	notif "github.com/libp2p/go-libp2p-routing/notifications"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21
)

Steven Allen's avatar
Steven Allen committed
22 23 24
// ErrNoPeersQueried is returned when we failed to connect to any peers.
var ErrNoPeersQueried = errors.New("failed to query any peers")

25
var maxQueryConcurrency = AlphaValue
26

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
type dhtQuery struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28
	dht         *IpfsDHT
29
	key         string    // the key we're querying for
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31
	qfunc       queryFunc // the function to execute per peer
	concurrency int       // the concurrency parameter
32 33 34
}

type dhtQueryResult struct {
35 36 37
	peer        *pstore.PeerInfo   // FindPeer
	closerPeers []*pstore.PeerInfo // *
	success     bool
Jeromy's avatar
Jeromy committed
38

39 40
	finalSet   *pset.PeerSet
	queriedSet *pset.PeerSet
41 42 43
}

// constructs query
44
func (dht *IpfsDHT) newQuery(k string, f queryFunc) *dhtQuery {
45 46
	return &dhtQuery{
		key:         k,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
		dht:         dht,
48 49 50
		qfunc:       f,
		concurrency: maxQueryConcurrency,
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51 52 53 54 55 56 57
}

// QueryFunc is a function that runs a particular query with a given peer.
// It returns either:
// - the value
// - a list of peers potentially better able to serve the query
// - an error
58
type queryFunc func(context.Context, peer.ID) (*dhtQueryResult, error)
59 60

// Run runs the query at hand. pass in a list of peers to use first.
61
func (q *dhtQuery) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
62 63 64 65 66
	if len(peers) == 0 {
		logger.Warning("Running query with no peers!")
		return nil, kb.ErrLookupFailure
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69 70 71 72
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	default:
	}

73 74 75
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

76 77
	runner := newQueryRunner(q)
	return runner.Run(ctx, peers)
78 79 80
}

type dhtQueryRunner struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81 82
	query          *dhtQuery        // query to run
	peersSeen      *pset.PeerSet    // all peers queried. prevent querying same peer 2x
83
	peersQueried   *pset.PeerSet    // peers successfully connected to and queried
84
	peersDialed    *dialQueue       // peers we have dialed to
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85 86
	peersToQuery   *queue.ChanQueue // peers remaining to be queried
	peersRemaining todoctr.Counter  // peersToQuery + currently processing
87

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88
	result *dhtQueryResult // query result
89

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
	rateLimit chan struct{} // processing semaphore
Jeromy's avatar
Jeromy committed
91
	log       logging.EventLogger
92

93 94
	runCtx context.Context

95
	proc process.Process
96 97 98
	sync.RWMutex
}

99 100
func newQueryRunner(q *dhtQuery) *dhtQueryRunner {
	proc := process.WithParent(process.Background())
101
	ctx := ctxproc.OnClosingContext(proc)
102 103
	peersToQuery := queue.NewChanQueue(ctx, queue.NewXORDistancePQ(string(q.key)))
	r := &dhtQueryRunner{
104 105
		query:          q,
		peersRemaining: todoctr.NewSyncCounter(),
106
		peersSeen:      pset.New(),
107
		peersQueried:   pset.New(),
108
		rateLimit:      make(chan struct{}, q.concurrency),
109
		peersToQuery:   peersToQuery,
110
		proc:           proc,
111
	}
112 113 114 115 116 117 118 119 120 121 122
	dq, err := newDialQueue(&dqParams{
		ctx:    ctx,
		target: q.key,
		in:     peersToQuery,
		dialFn: r.dialPeer,
		config: dqDefaultConfig(),
	})
	if err != nil {
		panic(err)
	}
	r.peersDialed = dq
123
	return r
124 125
}

126
func (r *dhtQueryRunner) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
Matt Joiner's avatar
Matt Joiner committed
127
	r.log = logger
128
	r.runCtx = ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129

130 131 132
	// setup concurrency rate limiting
	for i := 0; i < r.query.concurrency; i++ {
		r.rateLimit <- struct{}{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134
	}

135 136
	// add all the peers we got first.
	for _, p := range peers {
137
		r.addPeerToQuery(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138 139
	}

140 141 142 143 144
	// start the dial queue only after we've added the initial set of peers.
	// this is to avoid race conditions that could cause the peersRemaining todoctr
	// to be done too early if the initial dial fails before others make it into the queue.
	r.peersDialed.Start()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145
	// go do this thing.
146
	// do it as a child proc to make sure Run exits
147
	// ONLY AFTER spawn workers has exited.
148
	r.proc.Go(r.spawnWorkers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149 150

	// wait until they're done.
151
	var err error
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152

153 154 155
	// now, if the context finishes, close the proc.
	// we have to do it here because the logic before is setup, which
	// should run without closing the proc.
rht's avatar
rht committed
156
	ctxproc.CloseAfterContext(r.proc, ctx)
157

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	select {
159
	case <-r.peersRemaining.Done():
160
		r.proc.Close()
Steven Allen's avatar
Steven Allen committed
161 162 163 164
		if r.peersQueried.Size() == 0 {
			err = ErrNoPeersQueried
		} else {
			err = routing.ErrNotFound
165 166
		}

167
	case <-r.proc.Closed():
168
		err = r.runCtx.Err()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
	}
170

Steven Allen's avatar
Steven Allen committed
171 172 173
	r.RLock()
	defer r.RUnlock()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174 175
	if r.result != nil && r.result.success {
		return r.result, nil
176 177
	}

Jeromy's avatar
Jeromy committed
178
	return &dhtQueryResult{
179 180
		finalSet:   r.peersSeen,
		queriedSet: r.peersQueried,
Jeromy's avatar
Jeromy committed
181
	}, err
182 183
}

184
func (r *dhtQueryRunner) addPeerToQuery(next peer.ID) {
185
	// if new peer is ourselves...
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186
	if next == r.query.dht.self {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187
		r.log.Debug("addPeerToQuery skip self")
188 189 190
		return
	}

191
	if !r.peersSeen.TryAdd(next) {
192 193 194
		return
	}

195 196 197 198 199
	notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
		Type: notif.AddingPeer,
		ID:   next,
	})

200 201 202
	r.peersRemaining.Increment(1)
	select {
	case r.peersToQuery.EnqChan <- next:
203
	case <-r.proc.Closing():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
	}
205 206
}

207
func (r *dhtQueryRunner) spawnWorkers(proc process.Process) {
208 209 210 211 212
	for {
		select {
		case <-r.peersRemaining.Done():
			return

213
		case <-r.proc.Closing():
214 215
			return

Jeromy's avatar
Jeromy committed
216
		case <-r.rateLimit:
217
			ch := r.peersDialed.Consume()
Jeromy's avatar
Jeromy committed
218
			select {
219 220 221
			case p, ok := <-ch:
				if !ok {
					// this signals context cancellation.
222 223
					return
				}
Jeromy's avatar
Jeromy committed
224 225 226 227 228 229 230 231 232
				// do it as a child func to make sure Run exits
				// ONLY AFTER spawn workers has exited.
				proc.Go(func(proc process.Process) {
					r.queryPeer(proc, p)
				})
			case <-r.proc.Closing():
				return
			case <-r.peersRemaining.Done():
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233
			}
234 235 236
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237

238 239 240 241 242 243
func (r *dhtQueryRunner) dialPeer(ctx context.Context, p peer.ID) error {
	// short-circuit if we're already connected.
	if r.query.dht.host.Network().Connectedness(p) == inet.Connected {
		return nil
	}

Matt Joiner's avatar
Matt Joiner committed
244
	logger.Debug("not connected. dialing.")
245 246 247 248 249 250 251
	notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
		Type: notif.DialingPeer,
		ID:   p,
	})

	pi := pstore.PeerInfo{ID: p}
	if err := r.query.dht.host.Connect(ctx, pi); err != nil {
Matt Joiner's avatar
Matt Joiner committed
252
		logger.Debugf("error connecting: %s", err)
253 254 255 256 257 258
		notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
			ID:    p,
		})

259 260
		// This peer is dropping out of the race.
		r.peersRemaining.Decrement(1)
261 262
		return err
	}
Matt Joiner's avatar
Matt Joiner committed
263
	logger.Debugf("connected. dial success.")
264 265 266
	return nil
}

267
func (r *dhtQueryRunner) queryPeer(proc process.Process, p peer.ID) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
268 269
	// ok let's do this!

270
	// create a context from our proc.
271
	ctx := ctxproc.OnClosingContext(proc)
272

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
273 274
	// make sure we do this when we exit
	defer func() {
275
		// signal we're done processing peer p
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276 277 278 279
		r.peersRemaining.Decrement(1)
		r.rateLimit <- struct{}{}
	}()

280
	// finally, run the query against this peer
281
	res, err := r.query.qfunc(ctx, p)
282

283 284
	r.peersQueried.Add(p)

285
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
286
		logger.Debugf("ERROR worker for: %v %v", p, err)
287
	} else if res.success {
Matt Joiner's avatar
Matt Joiner committed
288
		logger.Debugf("SUCCESS worker for: %v %s", p, res)
289 290 291
		r.Lock()
		r.result = res
		r.Unlock()
292 293 294
		if res.peer != nil {
			r.query.dht.peerstore.AddAddrs(res.peer.ID, res.peer.Addrs, pstore.TempAddrTTL)
		}
295
		go r.proc.Close() // signal to everyone that we're done.
296
		// must be async, as we're one of the children, and Close blocks.
297

298
	} else if len(res.closerPeers) > 0 {
Matt Joiner's avatar
Matt Joiner committed
299
		logger.Debugf("PEERS CLOSER -- worker for: %v (%d closer peers)", p, len(res.closerPeers))
300
		for _, next := range res.closerPeers {
301
			if next.ID == r.query.dht.self { // don't add self.
Matt Joiner's avatar
Matt Joiner committed
302
				logger.Debugf("PEERS CLOSER -- worker for: %v found self", p)
303 304 305
				continue
			}

306
			// add their addresses to the dialer's peerstore
Jeromy's avatar
Jeromy committed
307
			r.query.dht.peerstore.AddAddrs(next.ID, next.Addrs, pstore.TempAddrTTL)
308
			r.addPeerToQuery(next.ID)
Matt Joiner's avatar
Matt Joiner committed
309
			logger.Debugf("PEERS CLOSER -- worker for: %v added %v (%v)", p, next.ID, next.Addrs)
310
		}
311
	} else {
Matt Joiner's avatar
Matt Joiner committed
312
		logger.Debugf("QUERY worker for: %v - not found, and no closer peers.", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313 314
	}
}