query.go 6.83 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

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
16
	ctxgroup "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
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 58 59
	runner := newQueryRunner(ctx, q)
	return runner.Run(peers)
}

type dhtQueryRunner struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61 62 63
	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
64

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69
	rateLimit chan struct{} // processing semaphore
	log       eventlog.EventLogger
70

71
	cg ctxgroup.ContextGroup
72 73 74 75 76 77 78 79
	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(),
80
		peersSeen:      pset.New(),
81
		rateLimit:      make(chan struct{}, q.concurrency),
82
		cg:             ctxgroup.WithContext(ctx),
83 84 85
	}
}

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

89 90 91 92
	if len(peers) == 0 {
		log.Warning("Running query with no peers!")
		return nil, nil
	}
93

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
	// go do this thing.
105 106 107
	// 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
108 109 110 111

	// so workers are working.

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

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

120 121 122 123 124 125
		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]
126 127
		}

128
	case <-r.cg.Closed():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130
		log.Debug("r.cg.Closed()")

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137
	if r.result != nil && r.result.success {
		return r.result, nil
138 139
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140
	return nil, err
141 142
}

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

150
	if !r.peersSeen.TryAdd(next) {
151 152 153 154 155 156
		return
	}

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

161
func (r *dhtQueryRunner) spawnWorkers(parent ctxgroup.ContextGroup) {
162
	for {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163

164 165 166 167
		select {
		case <-r.peersRemaining.Done():
			return

168
		case <-r.cg.Closing():
169 170
			return

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

			// 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)
			})
181 182 183
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194 195 196 197 198 199 200 201 202 203
	// 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.
204
	// FIXME abstract away into the network layer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205
	if conns := r.query.dht.host.Network().ConnsToPeer(p); len(conns) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206
		log.Infof("not connected. dialing.")
207 208 209
		// 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{}{}
210

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211 212
		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
213
			log.Debugf("Error connecting: %s", err)
214 215 216 217 218 219

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

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

230
	// finally, run the query against this peer
231
	res, err := r.query.qfunc(cg.Context(), p)
232 233

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

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

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

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