query.go 7.36 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"
5 6
	"sync"

7 8
	u "github.com/ipfs/go-ipfs-util"
	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 13 14 15
	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
16 17
	routing "github.com/libp2p/go-libp2p-routing"
	notif "github.com/libp2p/go-libp2p-routing/notifications"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
)

20
var maxQueryConcurrency = AlphaValue
21

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
type dhtQuery struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23
	dht         *IpfsDHT
24
	key         string    // the key we're querying for
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26
	qfunc       queryFunc // the function to execute per peer
	concurrency int       // the concurrency parameter
27 28 29
}

type dhtQueryResult struct {
Jeromy's avatar
Jeromy committed
30 31 32 33
	value         []byte            // GetValue
	peer          pstore.PeerInfo   // FindPeer
	providerPeers []pstore.PeerInfo // GetProviders
	closerPeers   []pstore.PeerInfo // *
34 35 36 37
	success       bool
}

// constructs query
38
func (dht *IpfsDHT) newQuery(k string, f queryFunc) *dhtQuery {
39 40
	return &dhtQuery{
		key:         k,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
		dht:         dht,
42 43 44
		qfunc:       f,
		concurrency: maxQueryConcurrency,
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45 46 47 48 49 50 51
}

// 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
52
type queryFunc func(context.Context, peer.ID) (*dhtQueryResult, error)
53 54

// Run runs the query at hand. pass in a list of peers to use first.
55
func (q *dhtQuery) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56 57 58 59 60 61
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	default:
	}

62 63 64
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

65 66
	runner := newQueryRunner(q)
	return runner.Run(ctx, peers)
67 68 69
}

type dhtQueryRunner struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70 71 72 73
	query          *dhtQuery        // query to run
	peersSeen      *pset.PeerSet    // all peers queried. prevent querying same peer 2x
	peersToQuery   *queue.ChanQueue // peers remaining to be queried
	peersRemaining todoctr.Counter  // peersToQuery + currently processing
74

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
	result *dhtQueryResult // query result
76
	errs   u.MultiErr      // result errors. maybe should be a map[peer.ID]error
77

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
	rateLimit chan struct{} // processing semaphore
Jeromy's avatar
Jeromy committed
79
	log       logging.EventLogger
80

81 82
	runCtx context.Context

83
	proc process.Process
84 85 86
	sync.RWMutex
}

87 88
func newQueryRunner(q *dhtQuery) *dhtQueryRunner {
	proc := process.WithParent(process.Background())
89
	ctx := ctxproc.OnClosingContext(proc)
90 91
	return &dhtQueryRunner{
		query:          q,
92
		peersToQuery:   queue.NewChanQueue(ctx, queue.NewXORDistancePQ(string(q.key))),
93
		peersRemaining: todoctr.NewSyncCounter(),
94
		peersSeen:      pset.New(),
95
		rateLimit:      make(chan struct{}, q.concurrency),
96
		proc:           proc,
97 98 99
	}
}

100
func (r *dhtQueryRunner) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	r.log = log
102
	r.runCtx = ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103

104 105 106 107
	if len(peers) == 0 {
		log.Warning("Running query with no peers!")
		return nil, nil
	}
108

109 110 111
	// setup concurrency rate limiting
	for i := 0; i < r.query.concurrency; i++ {
		r.rateLimit <- struct{}{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113
	}

114 115
	// add all the peers we got first.
	for _, p := range peers {
116
		r.addPeerToQuery(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117 118
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119
	// go do this thing.
120
	// do it as a child proc to make sure Run exits
121
	// ONLY AFTER spawn workers has exited.
122
	r.proc.Go(r.spawnWorkers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124 125 126

	// so workers are working.

	// wait until they're done.
127
	err := routing.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128

129 130 131
	// 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
132
	ctxproc.CloseAfterContext(r.proc, ctx)
133

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	select {
135
	case <-r.peersRemaining.Done():
136
		r.proc.Close()
137 138 139
		r.RLock()
		defer r.RUnlock()

140 141 142 143 144 145
		err = routing.ErrNotFound

		// if every query to every peer failed, something must be very wrong.
		if len(r.errs) > 0 && len(r.errs) == r.peersSeen.Size() {
			log.Debugf("query errs: %s", r.errs)
			err = r.errs[0]
146 147
		}

148
	case <-r.proc.Closed():
149 150
		r.RLock()
		defer r.RUnlock()
151
		err = context.DeadlineExceeded
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152
	}
153

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
	if r.result != nil && r.result.success {
		return r.result, nil
156 157
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	return nil, err
159 160
}

161
func (r *dhtQueryRunner) addPeerToQuery(next peer.ID) {
162
	// if new peer is ourselves...
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
	if next == r.query.dht.self {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
		r.log.Debug("addPeerToQuery skip self")
165 166 167
		return
	}

168
	if !r.peersSeen.TryAdd(next) {
169 170 171
		return
	}

172 173 174 175 176
	notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
		Type: notif.AddingPeer,
		ID:   next,
	})

177 178 179
	r.peersRemaining.Increment(1)
	select {
	case r.peersToQuery.EnqChan <- next:
180
	case <-r.proc.Closing():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181
	}
182 183
}

184
func (r *dhtQueryRunner) spawnWorkers(proc process.Process) {
185
	for {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186

187 188 189 190
		select {
		case <-r.peersRemaining.Done():
			return

191
		case <-r.proc.Closing():
192 193
			return

Jeromy's avatar
Jeromy committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
		case <-r.rateLimit:
			select {
			case p, more := <-r.peersToQuery.DeqChan:
				if !more {
					return // channel closed.
				}

				// 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
210
			}
211 212 213
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214

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

218
	// create a context from our proc.
219
	ctx := ctxproc.OnClosingContext(proc)
220

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222 223 224 225 226 227 228
	// make sure we do this when we exit
	defer func() {
		// signal we're done proccessing peer p
		r.peersRemaining.Decrement(1)
		r.rateLimit <- struct{}{}
	}()

	// make sure we're connected to the peer.
229
	// FIXME abstract away into the network layer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230
	if conns := r.query.dht.host.Network().ConnsToPeer(p); len(conns) == 0 {
Jeromy's avatar
Jeromy committed
231
		log.Debug("not connected. dialing.")
232 233 234 235 236

		notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
			Type: notif.DialingPeer,
			ID:   p,
		})
237 238 239
		// while we dial, we do not take up a rate limit. this is to allow
		// forward progress during potentially very high latency dials.
		r.rateLimit <- struct{}{}
240

Jeromy's avatar
Jeromy committed
241
		pi := pstore.PeerInfo{ID: p}
242 243

		if err := r.query.dht.host.Connect(ctx, pi); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
			log.Debugf("Error connecting: %s", err)
245

246
			notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
247 248
				Type:  notif.QueryError,
				Extra: err.Error(),
249
				ID:    p,
250 251
			})

252 253 254
			r.Lock()
			r.errs = append(r.errs, err)
			r.Unlock()
255
			<-r.rateLimit // need to grab it again, as we deferred.
256 257
			return
		}
258
		<-r.rateLimit // need to grab it again, as we deferred.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259
		log.Debugf("connected. dial success.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261

262
	// finally, run the query against this peer
263
	res, err := r.query.qfunc(ctx, p)
264 265

	if err != nil {
266
		log.Debugf("ERROR worker for: %v %v", p, err)
267 268 269 270 271
		r.Lock()
		r.errs = append(r.errs, err)
		r.Unlock()

	} else if res.success {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272
		log.Debugf("SUCCESS worker for: %v %s", p, res)
273 274 275
		r.Lock()
		r.result = res
		r.Unlock()
276
		go r.proc.Close() // signal to everyone that we're done.
277
		// must be async, as we're one of the children, and Close blocks.
278

279 280
	} else if len(res.closerPeers) > 0 {
		log.Debugf("PEERS CLOSER -- worker for: %v (%d closer peers)", p, len(res.closerPeers))
281
		for _, next := range res.closerPeers {
282 283 284 285 286
			if next.ID == r.query.dht.self { // dont add self.
				log.Debugf("PEERS CLOSER -- worker for: %v found self", p)
				continue
			}

287
			// add their addresses to the dialer's peerstore
Jeromy's avatar
Jeromy committed
288
			r.query.dht.peerstore.AddAddrs(next.ID, next.Addrs, pstore.TempAddrTTL)
289
			r.addPeerToQuery(next.ID)
290
			log.Debugf("PEERS CLOSER -- worker for: %v added %v (%v)", p, next.ID, next.Addrs)
291
		}
292 293
	} else {
		log.Debugf("QUERY worker for: %v - not found, and no closer peers.", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294 295
	}
}