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

import (
4 5
	"sync"

6
	notif "github.com/jbenet/go-ipfs/notifications"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7 8
	peer "github.com/jbenet/go-ipfs/p2p/peer"
	queue "github.com/jbenet/go-ipfs/p2p/peer/queue"
9
	"github.com/jbenet/go-ipfs/routing"
10
	eventlog "github.com/jbenet/go-ipfs/thirdparty/eventlog"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
	u "github.com/jbenet/go-ipfs/util"
12
	pset "github.com/jbenet/go-ipfs/util/peerset"
13
	todoctr "github.com/jbenet/go-ipfs/util/todocounter"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14

15
	ctxgroup "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
16
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
)

19
var maxQueryConcurrency = AlphaValue
20

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

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

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

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

// Run runs the query at hand. pass in a list of peers to use first.
54
func (q *dhtQuery) Run(ctx context.Context, peers []peer.ID) (*dhtQueryResult, error) {
55 56 57
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

58 59 60 61 62
	runner := newQueryRunner(ctx, q)
	return runner.Run(peers)
}

type dhtQueryRunner struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63 64 65 66
	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
67

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71 72
	rateLimit chan struct{} // processing semaphore
	log       eventlog.EventLogger
73

74
	cg ctxgroup.ContextGroup
75 76 77 78 79 80 81 82
	sync.RWMutex
}

func newQueryRunner(ctx context.Context, q *dhtQuery) *dhtQueryRunner {
	return &dhtQueryRunner{
		query:          q,
		peersToQuery:   queue.NewChanQueue(ctx, queue.NewXORDistancePQ(q.key)),
		peersRemaining: todoctr.NewSyncCounter(),
83
		peersSeen:      pset.New(),
84
		rateLimit:      make(chan struct{}, q.concurrency),
85
		cg:             ctxgroup.WithContext(ctx),
86 87 88
	}
}

89
func (r *dhtQueryRunner) Run(peers []peer.ID) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90 91
	r.log = log

92 93 94 95
	if len(peers) == 0 {
		log.Warning("Running query with no peers!")
		return nil, nil
	}
96

97 98 99
	// setup concurrency rate limiting
	for i := 0; i < r.query.concurrency; i++ {
		r.rateLimit <- struct{}{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100 101
	}

102 103
	// add all the peers we got first.
	for _, p := range peers {
104
		r.addPeerToQuery(r.cg.Context(), p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
	// go do this thing.
108 109 110
	// do it as a child func to make sure Run exits
	// ONLY AFTER spawn workers has exited.
	r.cg.AddChildFunc(r.spawnWorkers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112 113 114

	// so workers are working.

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
	select {
118
	case <-r.peersRemaining.Done():
119
		r.cg.Close()
120 121 122
		r.RLock()
		defer r.RUnlock()

123 124 125 126 127 128
		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]
129 130
		}

131
	case <-r.cg.Closed():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133
		log.Debug("r.cg.Closed()")

134 135
		r.RLock()
		defer r.RUnlock()
136
		err = r.cg.Context().Err() // collect the error.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	}
138

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140
	if r.result != nil && r.result.success {
		return r.result, nil
141 142
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
	return nil, err
144 145
}

146
func (r *dhtQueryRunner) addPeerToQuery(ctx context.Context, next peer.ID) {
147
	// if new peer is ourselves...
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
	if next == r.query.dht.self {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149
		r.log.Debug("addPeerToQuery skip self")
150 151 152
		return
	}

153
	if !r.peersSeen.TryAdd(next) {
154 155 156 157 158 159
		return
	}

	r.peersRemaining.Increment(1)
	select {
	case r.peersToQuery.EnqChan <- next:
160
	case <-ctx.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
	}
162 163
}

164
func (r *dhtQueryRunner) spawnWorkers(parent ctxgroup.ContextGroup) {
165
	for {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166

167 168 169 170
		select {
		case <-r.peersRemaining.Done():
			return

171
		case <-r.cg.Closing():
172 173
			return

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174 175 176 177
		case p, more := <-r.peersToQuery.DeqChan:
			if !more {
				return // channel closed.
			}
178 179 180 181 182 183

			// do it as a child func to make sure Run exits
			// ONLY AFTER spawn workers has exited.
			parent.AddChildFunc(func(cg ctxgroup.ContextGroup) {
				r.queryPeer(cg, p)
			})
184 185 186
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187

188
func (r *dhtQueryRunner) queryPeer(cg ctxgroup.ContextGroup, p peer.ID) {
189 190 191
	// make sure we rate limit concurrency.
	select {
	case <-r.rateLimit:
192
	case <-cg.Closing():
193 194 195 196
		r.peersRemaining.Decrement(1)
		return
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198 199 200 201 202 203 204 205 206
	// ok let's do this!

	// 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.
207
	// FIXME abstract away into the network layer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
	if conns := r.query.dht.host.Network().ConnsToPeer(p); len(conns) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
		log.Infof("not connected. dialing.")
210 211 212
		// 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{}{}
213

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214 215
		pi := peer.PeerInfo{ID: p}
		if err := r.query.dht.host.Connect(cg.Context(), pi); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
			log.Debugf("Error connecting: %s", err)
217 218 219 220 221 222

			notif.PublishQueryEvent(cg.Context(), &notif.QueryEvent{
				Type:  notif.QueryError,
				Extra: err.Error(),
			})

223 224 225
			r.Lock()
			r.errs = append(r.errs, err)
			r.Unlock()
226
			<-r.rateLimit // need to grab it again, as we deferred.
227 228
			return
		}
229
		<-r.rateLimit // need to grab it again, as we deferred.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230
		log.Debugf("connected. dial success.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232

233
	// finally, run the query against this peer
234
	res, err := r.query.qfunc(cg.Context(), p)
235 236

	if err != nil {
237
		log.Debugf("ERROR worker for: %v %v", p, err)
238 239 240 241 242
		r.Lock()
		r.errs = append(r.errs, err)
		r.Unlock()

	} else if res.success {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243
		log.Debugf("SUCCESS worker for: %v %s", p, res)
244 245 246
		r.Lock()
		r.result = res
		r.Unlock()
247 248
		go r.cg.Close() // signal to everyone that we're done.
		// must be async, as we're one of the children, and Close blocks.
249

250 251
	} else if len(res.closerPeers) > 0 {
		log.Debugf("PEERS CLOSER -- worker for: %v (%d closer peers)", p, len(res.closerPeers))
252
		for _, next := range res.closerPeers {
253 254 255 256 257
			if next.ID == r.query.dht.self { // dont add self.
				log.Debugf("PEERS CLOSER -- worker for: %v found self", p)
				continue
			}

258
			// add their addresses to the dialer's peerstore
259
			r.query.dht.peerstore.AddAddrs(next.ID, next.Addrs, peer.TempAddrTTL)
260
			r.addPeerToQuery(cg.Context(), next.ID)
261
			log.Debugf("PEERS CLOSER -- worker for: %v added %v (%v)", p, next.ID, next.Addrs)
262
		}
263 264
	} else {
		log.Debugf("QUERY worker for: %v - not found, and no closer peers.", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265 266
	}
}