query.go 7.29 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 16
	process "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	ctxproc "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/context"
17
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
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 24 25 26
	dht         *IpfsDHT
	key         u.Key     // the key we're querying for
	qfunc       queryFunc // the function to execute per peer
	concurrency int       // the concurrency parameter
27 28 29
}

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

// constructs query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
func (dht *IpfsDHT) newQuery(k u.Key, 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 79
	rateLimit chan struct{} // processing semaphore
	log       eventlog.EventLogger
80

81
	proc process.Process
82 83 84
	sync.RWMutex
}

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

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

101 102 103 104
	if len(peers) == 0 {
		log.Warning("Running query with no peers!")
		return nil, nil
	}
105

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

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

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

	// so workers are working.

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

126 127 128 129 130 131 132 133
	// 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.
	go func() {
		<-ctx.Done()
		r.proc.Close()
	}()

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 172 173 174
		return
	}

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

179
func (r *dhtQueryRunner) spawnWorkers(proc process.Process) {
180
	for {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181

182 183 184 185
		select {
		case <-r.peersRemaining.Done():
			return

186
		case <-r.proc.Closing():
187 188
			return

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189 190 191 192
		case p, more := <-r.peersToQuery.DeqChan:
			if !more {
				return // channel closed.
			}
193 194 195

			// do it as a child func to make sure Run exits
			// ONLY AFTER spawn workers has exited.
196 197
			proc.Go(func(proc process.Process) {
				r.queryPeer(proc, p)
198
			})
199 200 201
		}
	}
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202

203
func (r *dhtQueryRunner) queryPeer(proc process.Process, p peer.ID) {
204 205 206
	// make sure we rate limit concurrency.
	select {
	case <-r.rateLimit:
207
	case <-proc.Closing():
208 209 210 211
		r.peersRemaining.Decrement(1)
		return
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212 213
	// ok let's do this!

214 215 216
	// create a context from our proc.
	ctx := ctxproc.WithProcessClosing(context.Background(), proc)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217 218 219 220 221 222 223 224
	// 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.
225
	// FIXME abstract away into the network layer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
	if conns := r.query.dht.host.Network().ConnsToPeer(p); len(conns) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
		log.Infof("not connected. dialing.")
228 229 230
		// 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{}{}
231

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232
		pi := peer.PeerInfo{ID: p}
233 234

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

237
			notif.PublishQueryEvent(ctx, &notif.QueryEvent{
238 239 240 241
				Type:  notif.QueryError,
				Extra: err.Error(),
			})

242 243 244
			r.Lock()
			r.errs = append(r.errs, err)
			r.Unlock()
245
			<-r.rateLimit // need to grab it again, as we deferred.
246 247
			return
		}
248
		<-r.rateLimit // need to grab it again, as we deferred.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249
		log.Debugf("connected. dial success.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251

252
	// finally, run the query against this peer
253
	res, err := r.query.qfunc(ctx, p)
254 255

	if err != nil {
256
		log.Debugf("ERROR worker for: %v %v", p, err)
257 258 259 260 261
		r.Lock()
		r.errs = append(r.errs, err)
		r.Unlock()

	} else if res.success {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262
		log.Debugf("SUCCESS worker for: %v %s", p, res)
263 264 265
		r.Lock()
		r.result = res
		r.Unlock()
266
		go r.proc.Close() // signal to everyone that we're done.
267
		// must be async, as we're one of the children, and Close blocks.
268

269 270
	} else if len(res.closerPeers) > 0 {
		log.Debugf("PEERS CLOSER -- worker for: %v (%d closer peers)", p, len(res.closerPeers))
271
		for _, next := range res.closerPeers {
272 273 274 275 276
			if next.ID == r.query.dht.self { // dont add self.
				log.Debugf("PEERS CLOSER -- worker for: %v found self", p)
				continue
			}

277
			// add their addresses to the dialer's peerstore
278
			r.query.dht.peerstore.AddAddrs(next.ID, next.Addrs, peer.TempAddrTTL)
279
			r.addPeerToQuery(next.ID)
280
			log.Debugf("PEERS CLOSER -- worker for: %v added %v (%v)", p, next.ID, next.Addrs)
281
		}
282 283
	} else {
		log.Debugf("QUERY worker for: %v - not found, and no closer peers.", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284 285
	}
}