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

import (
4 5
	"sync"

6
	key "github.com/ipfs/go-ipfs/blocks/key"
7 8 9 10 11
	notif "github.com/ipfs/go-ipfs/notifications"
	"github.com/ipfs/go-ipfs/routing"
	u "github.com/ipfs/go-ipfs/util"
	pset "github.com/ipfs/go-ipfs/util/peerset"
	todoctr "github.com/ipfs/go-ipfs/util/todocounter"
Jeromy's avatar
Jeromy committed
12 13
	peer "gx/ipfs/QmZxtCsPRgCnCXwVPUjcBiFckkG5NMYM4Pthwe6X4C8uQq/go-libp2p/p2p/peer"
	queue "gx/ipfs/QmZxtCsPRgCnCXwVPUjcBiFckkG5NMYM4Pthwe6X4C8uQq/go-libp2p/p2p/peer/queue"
Jeromy's avatar
Jeromy committed
14
	logging "gx/ipfs/Qmazh5oNUVsDZTs2g59rq8aYQqwpss8tcUWQzor5sCCEuH/go-log"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15

16 17
	process "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	ctxproc "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/context"
18
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
)

21
var maxQueryConcurrency = AlphaValue
22

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

type dhtQueryResult struct {
31 32 33 34
	value         []byte          // GetValue
	peer          peer.PeerInfo   // FindPeer
	providerPeers []peer.PeerInfo // GetProviders
	closerPeers   []peer.PeerInfo // *
35 36 37 38
	success       bool
}

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

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

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

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

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

type dhtQueryRunner struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71 72 73 74
	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
75

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

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

82 83
	runCtx context.Context

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

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

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

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

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

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

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

	// so workers are working.

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

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

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

141 142 143 144 145 146
		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]
147 148
		}

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

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

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

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

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
		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
211
			}
212 213 214
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
215

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222 223 224 225 226 227 228 229
	// 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.
230
	// FIXME abstract away into the network layer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
	if conns := r.query.dht.host.Network().ConnsToPeer(p); len(conns) == 0 {
Jeromy's avatar
Jeromy committed
232
		log.Debug("not connected. dialing.")
233 234 235 236 237

		notif.PublishQueryEvent(r.runCtx, &notif.QueryEvent{
			Type: notif.DialingPeer,
			ID:   p,
		})
238 239 240
		// 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{}{}
241

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242
		pi := peer.PeerInfo{ID: p}
243 244

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

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

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

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

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

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

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

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