dial.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package p2p
  17. import (
  18. "container/heap"
  19. "crypto/rand"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "time"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/p2p/discover"
  26. "github.com/ethereum/go-ethereum/p2p/netutil"
  27. )
  28. const (
  29. // This is the amount of time spent waiting in between
  30. // redialing a certain node.
  31. dialHistoryExpiration = 30 * time.Second
  32. // Discovery lookups are throttled and can only run
  33. // once every few seconds.
  34. lookupInterval = 4 * time.Second
  35. // Endpoint resolution is throttled with bounded backoff.
  36. initialResolveDelay = 60 * time.Second
  37. maxResolveDelay = time.Hour
  38. )
  39. // dialstate schedules dials and discovery lookups.
  40. // it get's a chance to compute new tasks on every iteration
  41. // of the main loop in Server.run.
  42. type dialstate struct {
  43. maxDynDials int
  44. ntab discoverTable
  45. netrestrict *netutil.Netlist
  46. lookupRunning bool
  47. dialing map[discover.NodeID]connFlag
  48. lookupBuf []*discover.Node // current discovery lookup results
  49. randomNodes []*discover.Node // filled from Table
  50. static map[discover.NodeID]*dialTask
  51. hist *dialHistory
  52. }
  53. type discoverTable interface {
  54. Self() *discover.Node
  55. Close()
  56. Resolve(target discover.NodeID) *discover.Node
  57. Lookup(target discover.NodeID) []*discover.Node
  58. ReadRandomNodes([]*discover.Node) int
  59. }
  60. // the dial history remembers recent dials.
  61. type dialHistory []pastDial
  62. // pastDial is an entry in the dial history.
  63. type pastDial struct {
  64. id discover.NodeID
  65. exp time.Time
  66. }
  67. type task interface {
  68. Do(*Server)
  69. }
  70. // A dialTask is generated for each node that is dialed. Its
  71. // fields cannot be accessed while the task is running.
  72. type dialTask struct {
  73. flags connFlag
  74. dest *discover.Node
  75. lastResolved time.Time
  76. resolveDelay time.Duration
  77. }
  78. // discoverTask runs discovery table operations.
  79. // Only one discoverTask is active at any time.
  80. // discoverTask.Do performs a random lookup.
  81. type discoverTask struct {
  82. results []*discover.Node
  83. }
  84. // A waitExpireTask is generated if there are no other tasks
  85. // to keep the loop in Server.run ticking.
  86. type waitExpireTask struct {
  87. time.Duration
  88. }
  89. func newDialState(static []*discover.Node, ntab discoverTable, maxdyn int, netrestrict *netutil.Netlist) *dialstate {
  90. s := &dialstate{
  91. maxDynDials: maxdyn,
  92. ntab: ntab,
  93. netrestrict: netrestrict,
  94. static: make(map[discover.NodeID]*dialTask),
  95. dialing: make(map[discover.NodeID]connFlag),
  96. randomNodes: make([]*discover.Node, maxdyn/2),
  97. hist: new(dialHistory),
  98. }
  99. for _, n := range static {
  100. s.addStatic(n)
  101. }
  102. return s
  103. }
  104. func (s *dialstate) addStatic(n *discover.Node) {
  105. // This overwites the task instead of updating an existing
  106. // entry, giving users the opportunity to force a resolve operation.
  107. s.static[n.ID] = &dialTask{flags: staticDialedConn, dest: n}
  108. }
  109. func (s *dialstate) removeStatic(n *discover.Node) {
  110. // This removes a task so future attempts to connect will not be made.
  111. delete(s.static, n.ID)
  112. }
  113. func (s *dialstate) newTasks(nRunning int, peers map[discover.NodeID]*Peer, now time.Time) []task {
  114. var newtasks []task
  115. addDial := func(flag connFlag, n *discover.Node) bool {
  116. if err := s.checkDial(n, peers); err != nil {
  117. log.Trace("Skipping dial candidate", "id", n.ID, "addr", &net.TCPAddr{IP: n.IP, Port: int(n.TCP)}, "err", err)
  118. return false
  119. }
  120. s.dialing[n.ID] = flag
  121. newtasks = append(newtasks, &dialTask{flags: flag, dest: n})
  122. return true
  123. }
  124. // Compute number of dynamic dials necessary at this point.
  125. needDynDials := s.maxDynDials
  126. for _, p := range peers {
  127. if p.rw.is(dynDialedConn) {
  128. needDynDials--
  129. }
  130. }
  131. for _, flag := range s.dialing {
  132. if flag&dynDialedConn != 0 {
  133. needDynDials--
  134. }
  135. }
  136. // Expire the dial history on every invocation.
  137. s.hist.expire(now)
  138. // Create dials for static nodes if they are not connected.
  139. for id, t := range s.static {
  140. err := s.checkDial(t.dest, peers)
  141. switch err {
  142. case errNotWhitelisted, errSelf:
  143. log.Warn("Removing static dial candidate", "id", t.dest.ID, "addr", &net.TCPAddr{IP: t.dest.IP, Port: int(t.dest.TCP)}, "err", err)
  144. delete(s.static, t.dest.ID)
  145. case nil:
  146. s.dialing[id] = t.flags
  147. newtasks = append(newtasks, t)
  148. }
  149. }
  150. // Use random nodes from the table for half of the necessary
  151. // dynamic dials.
  152. randomCandidates := needDynDials / 2
  153. if randomCandidates > 0 {
  154. n := s.ntab.ReadRandomNodes(s.randomNodes)
  155. for i := 0; i < randomCandidates && i < n; i++ {
  156. if addDial(dynDialedConn, s.randomNodes[i]) {
  157. needDynDials--
  158. }
  159. }
  160. }
  161. // Create dynamic dials from random lookup results, removing tried
  162. // items from the result buffer.
  163. i := 0
  164. for ; i < len(s.lookupBuf) && needDynDials > 0; i++ {
  165. if addDial(dynDialedConn, s.lookupBuf[i]) {
  166. needDynDials--
  167. }
  168. }
  169. s.lookupBuf = s.lookupBuf[:copy(s.lookupBuf, s.lookupBuf[i:])]
  170. // Launch a discovery lookup if more candidates are needed.
  171. if len(s.lookupBuf) < needDynDials && !s.lookupRunning {
  172. s.lookupRunning = true
  173. newtasks = append(newtasks, &discoverTask{})
  174. }
  175. // Launch a timer to wait for the next node to expire if all
  176. // candidates have been tried and no task is currently active.
  177. // This should prevent cases where the dialer logic is not ticked
  178. // because there are no pending events.
  179. if nRunning == 0 && len(newtasks) == 0 && s.hist.Len() > 0 {
  180. t := &waitExpireTask{s.hist.min().exp.Sub(now)}
  181. newtasks = append(newtasks, t)
  182. }
  183. return newtasks
  184. }
  185. var (
  186. errSelf = errors.New("is self")
  187. errAlreadyDialing = errors.New("already dialing")
  188. errAlreadyConnected = errors.New("already connected")
  189. errRecentlyDialed = errors.New("recently dialed")
  190. errNotWhitelisted = errors.New("not contained in netrestrict whitelist")
  191. )
  192. func (s *dialstate) checkDial(n *discover.Node, peers map[discover.NodeID]*Peer) error {
  193. _, dialing := s.dialing[n.ID]
  194. switch {
  195. case dialing:
  196. return errAlreadyDialing
  197. case peers[n.ID] != nil:
  198. return errAlreadyConnected
  199. case s.ntab != nil && n.ID == s.ntab.Self().ID:
  200. return errSelf
  201. case s.netrestrict != nil && !s.netrestrict.Contains(n.IP):
  202. return errNotWhitelisted
  203. case s.hist.contains(n.ID):
  204. return errRecentlyDialed
  205. }
  206. return nil
  207. }
  208. func (s *dialstate) taskDone(t task, now time.Time) {
  209. switch t := t.(type) {
  210. case *dialTask:
  211. s.hist.add(t.dest.ID, now.Add(dialHistoryExpiration))
  212. delete(s.dialing, t.dest.ID)
  213. case *discoverTask:
  214. s.lookupRunning = false
  215. s.lookupBuf = append(s.lookupBuf, t.results...)
  216. }
  217. }
  218. func (t *dialTask) Do(srv *Server) {
  219. if t.dest.Incomplete() {
  220. if !t.resolve(srv) {
  221. return
  222. }
  223. }
  224. success := t.dial(srv, t.dest)
  225. // Try resolving the ID of static nodes if dialing failed.
  226. if !success && t.flags&staticDialedConn != 0 {
  227. if t.resolve(srv) {
  228. t.dial(srv, t.dest)
  229. }
  230. }
  231. }
  232. // resolve attempts to find the current endpoint for the destination
  233. // using discovery.
  234. //
  235. // Resolve operations are throttled with backoff to avoid flooding the
  236. // discovery network with useless queries for nodes that don't exist.
  237. // The backoff delay resets when the node is found.
  238. func (t *dialTask) resolve(srv *Server) bool {
  239. if srv.ntab == nil {
  240. log.Debug("Can't resolve node", "id", t.dest.ID, "err", "discovery is disabled")
  241. return false
  242. }
  243. if t.resolveDelay == 0 {
  244. t.resolveDelay = initialResolveDelay
  245. }
  246. if time.Since(t.lastResolved) < t.resolveDelay {
  247. return false
  248. }
  249. resolved := srv.ntab.Resolve(t.dest.ID)
  250. t.lastResolved = time.Now()
  251. if resolved == nil {
  252. t.resolveDelay *= 2
  253. if t.resolveDelay > maxResolveDelay {
  254. t.resolveDelay = maxResolveDelay
  255. }
  256. log.Debug("Resolving node failed", "id", t.dest.ID, "newdelay", t.resolveDelay)
  257. return false
  258. }
  259. // The node was found.
  260. t.resolveDelay = initialResolveDelay
  261. t.dest = resolved
  262. log.Debug("Resolved node", "id", t.dest.ID, "addr", &net.TCPAddr{IP: t.dest.IP, Port: int(t.dest.TCP)})
  263. return true
  264. }
  265. // dial performs the actual connection attempt.
  266. func (t *dialTask) dial(srv *Server, dest *discover.Node) bool {
  267. addr := &net.TCPAddr{IP: dest.IP, Port: int(dest.TCP)}
  268. fd, err := srv.Dialer.Dial("tcp", addr.String())
  269. if err != nil {
  270. log.Trace("Dial error", "task", t, "err", err)
  271. return false
  272. }
  273. mfd := newMeteredConn(fd, false)
  274. srv.setupConn(mfd, t.flags, dest)
  275. return true
  276. }
  277. func (t *dialTask) String() string {
  278. return fmt.Sprintf("%v %x %v:%d", t.flags, t.dest.ID[:8], t.dest.IP, t.dest.TCP)
  279. }
  280. func (t *discoverTask) Do(srv *Server) {
  281. // newTasks generates a lookup task whenever dynamic dials are
  282. // necessary. Lookups need to take some time, otherwise the
  283. // event loop spins too fast.
  284. next := srv.lastLookup.Add(lookupInterval)
  285. if now := time.Now(); now.Before(next) {
  286. time.Sleep(next.Sub(now))
  287. }
  288. srv.lastLookup = time.Now()
  289. var target discover.NodeID
  290. rand.Read(target[:])
  291. t.results = srv.ntab.Lookup(target)
  292. }
  293. func (t *discoverTask) String() string {
  294. s := "discovery lookup"
  295. if len(t.results) > 0 {
  296. s += fmt.Sprintf(" (%d results)", len(t.results))
  297. }
  298. return s
  299. }
  300. func (t waitExpireTask) Do(*Server) {
  301. time.Sleep(t.Duration)
  302. }
  303. func (t waitExpireTask) String() string {
  304. return fmt.Sprintf("wait for dial hist expire (%v)", t.Duration)
  305. }
  306. // Use only these methods to access or modify dialHistory.
  307. func (h dialHistory) min() pastDial {
  308. return h[0]
  309. }
  310. func (h *dialHistory) add(id discover.NodeID, exp time.Time) {
  311. heap.Push(h, pastDial{id, exp})
  312. }
  313. func (h dialHistory) contains(id discover.NodeID) bool {
  314. for _, v := range h {
  315. if v.id == id {
  316. return true
  317. }
  318. }
  319. return false
  320. }
  321. func (h *dialHistory) expire(now time.Time) {
  322. for h.Len() > 0 && h.min().exp.Before(now) {
  323. heap.Pop(h)
  324. }
  325. }
  326. // heap.Interface boilerplate
  327. func (h dialHistory) Len() int { return len(h) }
  328. func (h dialHistory) Less(i, j int) bool { return h[i].exp.Before(h[j].exp) }
  329. func (h dialHistory) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  330. func (h *dialHistory) Push(x interface{}) {
  331. *h = append(*h, x.(pastDial))
  332. }
  333. func (h *dialHistory) Pop() interface{} {
  334. old := *h
  335. n := len(old)
  336. x := old[n-1]
  337. *h = old[0 : n-1]
  338. return x
  339. }