dial.go 9.4 KB

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