query.go 14.6 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"
Steven Allen's avatar
Steven Allen committed
5
	"errors"
Adin Schmahmann's avatar
Adin Schmahmann committed
6
	"fmt"
7
	"math"
8
	"sync"
Aarsh Shah's avatar
Aarsh Shah committed
9
	"time"
10 11

	"github.com/google/uuid"
Adin Schmahmann's avatar
Adin Schmahmann committed
12

13 14
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
15
	pstore "github.com/libp2p/go-libp2p-core/peerstore"
Adin Schmahmann's avatar
Adin Schmahmann committed
16
	"github.com/libp2p/go-libp2p-core/routing"
17

Adin Schmahmann's avatar
Adin Schmahmann committed
18
	"github.com/libp2p/go-libp2p-kad-dht/qpeerset"
19
	kb "github.com/libp2p/go-libp2p-kbucket"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21
)

Steven Allen's avatar
Steven Allen committed
22 23 24
// ErrNoPeersQueried is returned when we failed to connect to any peers.
var ErrNoPeersQueried = errors.New("failed to query any peers")

Adin Schmahmann's avatar
Adin Schmahmann committed
25
type queryFn func(context.Context, peer.ID) ([]*peer.AddrInfo, error)
Adin Schmahmann's avatar
Adin Schmahmann committed
26
type stopFn func() bool
27

Aarsh Shah's avatar
Aarsh Shah committed
28
// query represents a single DHT query.
Adin Schmahmann's avatar
Adin Schmahmann committed
29
type query struct {
30 31 32 33 34 35
	// unique identifier for the lookup instance
	id uuid.UUID

	// target key for the lookup
	key string

36 37
	// the query context.
	ctx context.Context
Adin Schmahmann's avatar
Adin Schmahmann committed
38

Adin Schmahmann's avatar
Adin Schmahmann committed
39
	dht *IpfsDHT
Jeromy's avatar
Jeromy committed
40

Adin Schmahmann's avatar
Adin Schmahmann committed
41 42 43
	// seedPeers is the set of peers that seed the query
	seedPeers []peer.ID

44 45 46
	// peerTimes contains the duration of each successful query to a peer
	peerTimes map[peer.ID]time.Duration

Adin Schmahmann's avatar
Adin Schmahmann committed
47 48 49 50 51 52
	// queryPeers is the set of peers known by this query and their respective states.
	queryPeers *qpeerset.QueryPeerset

	// terminated is set when the first worker thread encounters the termination condition.
	// Its role is to make sure that once termination is determined, it is sticky.
	terminated bool
53

54 55 56
	// waitGroup ensures lookup does not end until all query goroutines complete.
	waitGroup sync.WaitGroup

57 58 59 60 61
	// the function that will be used to query a single peer.
	queryFn queryFn

	// stopFn is used to determine if we should stop the WHOLE disjoint query.
	stopFn stopFn
62 63
}

Adin Schmahmann's avatar
Adin Schmahmann committed
64
type lookupWithFollowupResult struct {
Aarsh Shah's avatar
Aarsh Shah committed
65 66
	peers []peer.ID            // the top K not unreachable peers at the end of the query
	state []qpeerset.PeerState // the peer states at the end of the query
Adin Schmahmann's avatar
Adin Schmahmann committed
67

Adin Schmahmann's avatar
Adin Schmahmann committed
68 69 70 71 72 73 74 75 76 77 78 79
	// indicates that neither the lookup nor the followup has been prematurely terminated by an external condition such
	// as context cancellation or the stop function being called.
	completed bool
}

// runLookupWithFollowup executes the lookup on the target using the given query function and stopping when either the
// context is cancelled or the stop function returns true. Note: if the stop function is not sticky, i.e. it does not
// return true every time after the first time it returns true, it is not guaranteed to cause a stop to occur just
// because it momentarily returns true.
//
// After the lookup is complete the query function is run (unless stopped) against all of the top K peers from the
// lookup that have not already been successfully queried.
Aarsh Shah's avatar
Aarsh Shah committed
80
func (dht *IpfsDHT) runLookupWithFollowup(ctx context.Context, target string, queryFn queryFn, stopFn stopFn) (*lookupWithFollowupResult, error) {
Adin Schmahmann's avatar
Adin Schmahmann committed
81
	// run the query
Aarsh Shah's avatar
Aarsh Shah committed
82
	lookupRes, err := dht.runQuery(ctx, target, queryFn, stopFn)
Adin Schmahmann's avatar
Adin Schmahmann committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
	if err != nil {
		return nil, err
	}

	// query all of the top K peers we've either Heard about or have outstanding queries we're Waiting on.
	// This ensures that all of the top K results have been queried which adds to resiliency against churn for query
	// functions that carry state (e.g. FindProviders and GetValue) as well as establish connections that are needed
	// by stateless query functions (e.g. GetClosestPeers and therefore Provide and PutValue)
	queryPeers := make([]peer.ID, 0, len(lookupRes.peers))
	for i, p := range lookupRes.peers {
		if state := lookupRes.state[i]; state == qpeerset.PeerHeard || state == qpeerset.PeerWaiting {
			queryPeers = append(queryPeers, p)
		}
	}

	if len(queryPeers) == 0 {
		return lookupRes, nil
	}

	// return if the lookup has been externally stopped
	if ctx.Err() != nil || stopFn() {
		lookupRes.completed = false
		return lookupRes, nil
	}

	doneCh := make(chan struct{}, len(queryPeers))
	followUpCtx, cancelFollowUp := context.WithCancel(ctx)
110
	defer cancelFollowUp()
Adin Schmahmann's avatar
Adin Schmahmann committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	for _, p := range queryPeers {
		qp := p
		go func() {
			_, _ = queryFn(followUpCtx, qp)
			doneCh <- struct{}{}
		}()
	}

	// wait for all queries to complete before returning, aborting ongoing queries if we've been externally stopped
processFollowUp:
	for i := 0; i < len(queryPeers); i++ {
		select {
		case <-doneCh:
			if stopFn() {
				cancelFollowUp()
				if i < len(queryPeers)-1 {
					lookupRes.completed = false
				}
				break processFollowUp
			}
		case <-ctx.Done():
			lookupRes.completed = false
			break processFollowUp
		}
	}

	return lookupRes, nil
}

Aarsh Shah's avatar
Aarsh Shah committed
140
func (dht *IpfsDHT) runQuery(ctx context.Context, target string, queryFn queryFn, stopFn stopFn) (*lookupWithFollowupResult, error) {
Max Inden's avatar
Max Inden committed
141
	// pick the K closest peers to the key in our Routing table.
Adin Schmahmann's avatar
Adin Schmahmann committed
142 143
	targetKadID := kb.ConvertKey(target)
	seedPeers := dht.routingTable.NearestPeers(targetKadID, dht.bucketSize)
144 145 146 147 148 149 150
	if len(seedPeers) == 0 {
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
			Extra: kb.ErrLookupFailure.Error(),
		})
		return nil, kb.ErrLookupFailure
	}
Adin Schmahmann's avatar
Adin Schmahmann committed
151

Aarsh Shah's avatar
Aarsh Shah committed
152
	q := &query{
153 154
		id:         uuid.New(),
		key:        target,
155
		ctx:        ctx,
Aarsh Shah's avatar
Aarsh Shah committed
156 157 158
		dht:        dht,
		queryPeers: qpeerset.NewQueryPeerset(target),
		seedPeers:  seedPeers,
159
		peerTimes:  make(map[peer.ID]time.Duration),
Aarsh Shah's avatar
Aarsh Shah committed
160 161 162
		terminated: false,
		queryFn:    queryFn,
		stopFn:     stopFn,
163 164
	}

Aarsh Shah's avatar
Aarsh Shah committed
165
	// run the query
166 167 168 169 170
	q.run()

	if ctx.Err() == nil {
		q.recordValuablePeers()
	}
171

Aarsh Shah's avatar
Aarsh Shah committed
172
	res := q.constructLookupResult(targetKadID)
Adin Schmahmann's avatar
Adin Schmahmann committed
173
	return res, nil
174 175
}

Aarsh Shah's avatar
Aarsh Shah committed
176
func (q *query) recordPeerIsValuable(p peer.ID) {
177 178 179 180 181 182 183 184 185 186 187 188
	if !q.dht.routingTable.UpdateLastUsefulAt(p, time.Now()) {
		// not in routing table
		return
	}

	// Protect useful peers, when they're actually useful. This will last
	// through disconnects. However, we'll still evict them if they keep
	// disconnecting from us.
	//
	// Restrict to buckets 0, 1 (75% of requests, max 40 peers), so we don't
	// protect _too_ many peers.
	commonPrefixLen := kb.CommonPrefixLen(q.dht.selfKey, kb.ConvertPeerID(p))
Steven Allen's avatar
Steven Allen committed
189
	cmgr := q.dht.host.ConnManager()
190
	if commonPrefixLen < usefulConnMgrProtectedBuckets {
Steven Allen's avatar
Steven Allen committed
191 192 193
		cmgr.Protect(p, dhtUsefulTag)
	} else {
		cmgr.TagPeer(p, dhtUsefulTag, usefulConnMgrScore)
194
	}
Aarsh Shah's avatar
Aarsh Shah committed
195
}
196 197

func (q *query) recordValuablePeers() {
198 199 200 201 202 203 204 205 206 207 208 209 210 211
	// Valuable peers algorithm:
	// Label the seed peer that responded to a query in the shortest amount of time as the "most valuable peer" (MVP)
	// Each seed peer that responded to a query within some range (i.e. 2x) of the MVP's time is a valuable peer
	// Mark the MVP and all the other valuable peers as valuable
	mvpDuration := time.Duration(math.MaxInt64)
	for _, p := range q.seedPeers {
		if queryTime, ok := q.peerTimes[p]; ok && queryTime < mvpDuration {
			mvpDuration = queryTime
		}
	}

	for _, p := range q.seedPeers {
		if queryTime, ok := q.peerTimes[p]; ok && queryTime < mvpDuration*2 {
			q.recordPeerIsValuable(p)
212 213 214 215
		}
	}
}

Adin Schmahmann's avatar
Adin Schmahmann committed
216
// constructLookupResult takes the query information and uses it to construct the lookup result
Aarsh Shah's avatar
Aarsh Shah committed
217 218
func (q *query) constructLookupResult(target kb.ID) *lookupWithFollowupResult {
	// determine if the query terminated early
Adin Schmahmann's avatar
Adin Schmahmann committed
219
	completed := true
Aarsh Shah's avatar
Aarsh Shah committed
220

221 222 223 224
	// Lookup and starvation are both valid ways for a lookup to complete. (Starvation does not imply failure.)
	// Lookup termination (as defined in isLookupTermination) is not possible in small networks.
	// Starvation is a successful query termination in small networks.
	if !(q.isLookupTermination() || q.isStarvationTermination()) {
Aarsh Shah's avatar
Aarsh Shah committed
225
		completed = false
Adin Schmahmann's avatar
Adin Schmahmann committed
226
	}
227

Aarsh Shah's avatar
Aarsh Shah committed
228
	// extract the top K not unreachable peers
Adin Schmahmann's avatar
Adin Schmahmann committed
229 230
	var peers []peer.ID
	peerState := make(map[peer.ID]qpeerset.PeerState)
Aarsh Shah's avatar
Aarsh Shah committed
231 232 233 234 235
	qp := q.queryPeers.GetClosestNotUnreachable(q.dht.bucketSize)
	for _, p := range qp {
		state := q.queryPeers.GetState(p)
		peerState[p] = state
		peers = append(peers, p)
236 237
	}

Adin Schmahmann's avatar
Adin Schmahmann committed
238 239
	// get the top K overall peers
	sortedPeers := kb.SortClosestPeers(peers, target)
Aarsh Shah's avatar
Aarsh Shah committed
240 241
	if len(sortedPeers) > q.dht.bucketSize {
		sortedPeers = sortedPeers[:q.dht.bucketSize]
242 243
	}

Aarsh Shah's avatar
Aarsh Shah committed
244
	// return the top K not unreachable peers as well as their states at the end of the query
Adin Schmahmann's avatar
Adin Schmahmann committed
245 246 247 248 249 250 251 252 253
	res := &lookupWithFollowupResult{
		peers:     sortedPeers,
		state:     make([]qpeerset.PeerState, len(sortedPeers)),
		completed: completed,
	}

	for i, p := range sortedPeers {
		res.state[i] = peerState[p]
	}
254 255

	return res
Adin Schmahmann's avatar
Adin Schmahmann committed
256
}
257

Adin Schmahmann's avatar
Adin Schmahmann committed
258
type queryUpdate struct {
259 260 261 262 263
	cause         peer.ID
	heard         []peer.ID
	queried       []peer.ID
	unreachable   []peer.ID
	queryDuration time.Duration
Adin Schmahmann's avatar
Adin Schmahmann committed
264
}
265

266
func (q *query) run() {
Adin Schmahmann's avatar
Adin Schmahmann committed
267 268
	pathCtx, cancelPath := context.WithCancel(q.ctx)
	defer cancelPath()
269

Adin Schmahmann's avatar
Adin Schmahmann committed
270
	alpha := q.dht.alpha
271

Adin Schmahmann's avatar
Adin Schmahmann committed
272
	ch := make(chan *queryUpdate, alpha)
273
	ch <- &queryUpdate{cause: q.dht.self, heard: q.seedPeers}
274

275 276
	// return only once all outstanding queries have completed.
	defer q.waitGroup.Wait()
Adin Schmahmann's avatar
Adin Schmahmann committed
277
	for {
278
		var cause peer.ID
Adin Schmahmann's avatar
Adin Schmahmann committed
279 280
		select {
		case update := <-ch:
281 282
			q.updateState(pathCtx, update)
			cause = update.cause
Adin Schmahmann's avatar
Adin Schmahmann committed
283
		case <-pathCtx.Done():
284
			q.terminate(pathCtx, cancelPath, LookupCancelled)
Adin Schmahmann's avatar
Adin Schmahmann committed
285 286
		}

Adin Schmahmann's avatar
Adin Schmahmann committed
287
		// termination is triggered on end-of-lookup conditions or starvation of unused peers
288 289 290
		if ready, reason := q.isReadyToTerminate(); ready {
			q.terminate(pathCtx, cancelPath, reason)
		}
Adin Schmahmann's avatar
Adin Schmahmann committed
291

292 293
		if q.terminated {
			return
Adin Schmahmann's avatar
Adin Schmahmann committed
294 295 296 297 298 299 300 301
		}

		// if all "threads" are busy, wait until someone finishes
		if q.queryPeers.NumWaiting() >= alpha {
			continue
		}

		// spawn new queries, up to the parallelism allowance
302 303 304 305 306
		// calculate the maximum number of queries we could be spawning.
		// Note: NumWaiting will be updated in spawnQuery
		maxNumQueriesToSpawn := alpha - q.queryPeers.NumWaiting()
		// try spawning the queries, if there are no available peers to query then we won't spawn them
		for j := 0; j < maxNumQueriesToSpawn; j++ {
307
			q.spawnQuery(pathCtx, cause, ch)
Adin Schmahmann's avatar
Adin Schmahmann committed
308 309 310 311
		}
	}
}

312 313
// spawnQuery starts one query, if an available heard peer is found
func (q *query) spawnQuery(ctx context.Context, cause peer.ID, ch chan<- *queryUpdate) {
Alan Shaw's avatar
Alan Shaw committed
314 315
	peers := q.queryPeers.GetSortedHeard()
	if len(peers) == 0 {
Adin Schmahmann's avatar
Adin Schmahmann committed
316 317
		return
	}
Alan Shaw's avatar
Alan Shaw committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

	PublishLookupEvent(ctx,
		NewLookupEvent(
			q.dht.self,
			q.id,
			q.key,
			NewLookupUpdateEvent(
				cause,
				q.queryPeers.GetReferrer(peers[0]),
				nil,                 // heard
				[]peer.ID{peers[0]}, // waiting
				nil,                 // queried
				nil,                 // unreachable
			),
			nil,
			nil,
		),
	)
	q.queryPeers.SetState(peers[0], qpeerset.PeerWaiting)
	q.waitGroup.Add(1)
	go q.queryPeer(ctx, ch, peers[0])
Adin Schmahmann's avatar
Adin Schmahmann committed
339 340
}

341
func (q *query) isReadyToTerminate() (bool, LookupTerminationReason) {
Adin Schmahmann's avatar
Adin Schmahmann committed
342 343
	// give the application logic a chance to terminate
	if q.stopFn() {
344
		return true, LookupStopped
Adin Schmahmann's avatar
Adin Schmahmann committed
345 346
	}
	if q.isStarvationTermination() {
347
		return true, LookupStarvation
Adin Schmahmann's avatar
Adin Schmahmann committed
348 349
	}
	if q.isLookupTermination() {
350
		return true, LookupCompleted
Adin Schmahmann's avatar
Adin Schmahmann committed
351
	}
352
	return false, -1
Adin Schmahmann's avatar
Adin Schmahmann committed
353 354 355 356 357
}

// From the set of all nodes that are not unreachable,
// if the closest beta nodes are all queried, the lookup can terminate.
func (q *query) isLookupTermination() bool {
Steven Allen's avatar
Steven Allen committed
358
	peers := q.queryPeers.GetClosestNotUnreachable(q.dht.beta)
Adin Schmahmann's avatar
Adin Schmahmann committed
359 360 361
	for _, p := range peers {
		if q.queryPeers.GetState(p) != qpeerset.PeerQueried {
			return false
Adin Schmahmann's avatar
Adin Schmahmann committed
362
		}
363
	}
Adin Schmahmann's avatar
Adin Schmahmann committed
364 365 366 367 368
	return true
}

func (q *query) isStarvationTermination() bool {
	return q.queryPeers.NumHeard() == 0 && q.queryPeers.NumWaiting() == 0
369 370
}

371 372 373 374
func (q *query) terminate(ctx context.Context, cancel context.CancelFunc, reason LookupTerminationReason) {
	if q.terminated {
		return
	}
Alan Shaw's avatar
Alan Shaw committed
375 376 377 378 379 380 381 382 383 384 385 386 387

	PublishLookupEvent(ctx,
		NewLookupEvent(
			q.dht.self,
			q.id,
			q.key,
			nil,
			nil,
			NewLookupTerminateEvent(reason),
		),
	)
	cancel() // abort outstanding queries
	q.terminated = true
388 389
}

Adin Schmahmann's avatar
Adin Schmahmann committed
390 391
// queryPeer queries a single peer and reports its findings on the channel.
// queryPeer does not access the query state in queryPeers!
392 393 394
func (q *query) queryPeer(ctx context.Context, ch chan<- *queryUpdate, p peer.ID) {
	defer q.waitGroup.Done()
	dialCtx, queryCtx := ctx, ctx
Adin Schmahmann's avatar
Adin Schmahmann committed
395

396
	startQuery := time.Now()
397
	// dial the peer
Adin Schmahmann's avatar
Adin Schmahmann committed
398
	if err := q.dht.dialPeer(dialCtx, p); err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
399 400 401 402
		// remove the peer if there was a dial failure..but not because of a context cancellation
		if dialCtx.Err() == nil {
			q.dht.peerStoppedDHT(q.dht.ctx, p)
		}
403
		ch <- &queryUpdate{cause: p, unreachable: []peer.ID{p}}
Adin Schmahmann's avatar
Adin Schmahmann committed
404
		return
Adin Schmahmann's avatar
Adin Schmahmann committed
405
	}
406 407

	// send query RPC to the remote peer
Adin Schmahmann's avatar
Adin Schmahmann committed
408 409
	newPeers, err := q.queryFn(queryCtx, p)
	if err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
410 411 412
		if queryCtx.Err() == nil {
			q.dht.peerStoppedDHT(q.dht.ctx, p)
		}
413
		ch <- &queryUpdate{cause: p, unreachable: []peer.ID{p}}
Adin Schmahmann's avatar
Adin Schmahmann committed
414
		return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
415
	}
416

417 418
	queryDuration := time.Since(startQuery)

Aarsh Shah's avatar
Aarsh Shah committed
419 420 421
	// query successful, try to add to RT
	q.dht.peerFound(q.dht.ctx, p, true)

Adin Schmahmann's avatar
Adin Schmahmann committed
422 423
	// process new peers
	saw := []peer.ID{}
Adin Schmahmann's avatar
Adin Schmahmann committed
424 425 426 427 428
	for _, next := range newPeers {
		if next.ID == q.dht.self { // don't add self.
			logger.Debugf("PEERS CLOSER -- worker for: %v found self", p)
			continue
		}
429

430 431 432 433
		// add any other know addresses for the candidate peer.
		curInfo := q.dht.peerstore.PeerInfo(next.ID)
		next.Addrs = append(next.Addrs, curInfo.Addrs...)

Adin Schmahmann's avatar
Adin Schmahmann committed
434
		// add their addresses to the dialer's peerstore
435
		if q.dht.queryPeerFilter(q.dht, *next) {
436
			q.dht.maybeAddAddrs(next.ID, next.Addrs, pstore.TempAddrTTL)
437 438
			saw = append(saw, next.ID)
		}
439
	}
Adin Schmahmann's avatar
Adin Schmahmann committed
440

441
	ch <- &queryUpdate{cause: p, heard: saw, queried: []peer.ID{p}, queryDuration: queryDuration}
Adin Schmahmann's avatar
Adin Schmahmann committed
442
}
443

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
func (q *query) updateState(ctx context.Context, up *queryUpdate) {
	if q.terminated {
		panic("update should not be invoked after the logical lookup termination")
	}
	PublishLookupEvent(ctx,
		NewLookupEvent(
			q.dht.self,
			q.id,
			q.key,
			nil,
			NewLookupUpdateEvent(
				up.cause,
				up.cause,
				up.heard,       // heard
				nil,            // waiting
				up.queried,     // queried
				up.unreachable, // unreachable
			),
			nil,
		),
	)
	for _, p := range up.heard {
Adin Schmahmann's avatar
Adin Schmahmann committed
466 467 468
		if p == q.dht.self { // don't add self.
			continue
		}
469
		q.queryPeers.TryAdd(p, up.cause)
Adin Schmahmann's avatar
Adin Schmahmann committed
470 471 472 473 474 475 476
	}
	for _, p := range up.queried {
		if p == q.dht.self { // don't add self.
			continue
		}
		if st := q.queryPeers.GetState(p); st == qpeerset.PeerWaiting {
			q.queryPeers.SetState(p, qpeerset.PeerQueried)
477
			q.peerTimes[p] = up.queryDuration
Adin Schmahmann's avatar
Adin Schmahmann committed
478 479 480 481 482 483 484 485 486 487 488 489 490
		} else {
			panic(fmt.Errorf("kademlia protocol error: tried to transition to the queried state from state %v", st))
		}
	}
	for _, p := range up.unreachable {
		if p == q.dht.self { // don't add self.
			continue
		}
		if st := q.queryPeers.GetState(p); st == qpeerset.PeerWaiting {
			q.queryPeers.SetState(p, qpeerset.PeerUnreachable)
		} else {
			panic(fmt.Errorf("kademlia protocol error: tried to transition to the unreachable state from state %v", st))
		}
491
	}
492
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
493

Adin Schmahmann's avatar
Adin Schmahmann committed
494
func (dht *IpfsDHT) dialPeer(ctx context.Context, p peer.ID) error {
495
	// short-circuit if we're already connected.
Adin Schmahmann's avatar
Adin Schmahmann committed
496
	if dht.host.Network().Connectedness(p) == network.Connected {
497 498 499
		return nil
	}

Matt Joiner's avatar
Matt Joiner committed
500
	logger.Debug("not connected. dialing.")
Adin Schmahmann's avatar
Adin Schmahmann committed
501
	routing.PublishQueryEvent(ctx, &routing.QueryEvent{
502
		Type: routing.DialingPeer,
503 504 505
		ID:   p,
	})

506
	pi := peer.AddrInfo{ID: p}
Adin Schmahmann's avatar
Adin Schmahmann committed
507
	if err := dht.host.Connect(ctx, pi); err != nil {
Matt Joiner's avatar
Matt Joiner committed
508
		logger.Debugf("error connecting: %s", err)
Adin Schmahmann's avatar
Adin Schmahmann committed
509
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
510
			Type:  routing.QueryError,
511 512 513 514 515 516
			Extra: err.Error(),
			ID:    p,
		})

		return err
	}
Matt Joiner's avatar
Matt Joiner committed
517
	logger.Debugf("connected. dial success.")
518 519
	return nil
}