dial.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. )
  35. // dialstate schedules dials and discovery lookups.
  36. // it get's a chance to compute new tasks on every iteration
  37. // of the main loop in Server.run.
  38. type dialstate struct {
  39. maxDynDials int
  40. ntab discoverTable
  41. lookupRunning bool
  42. dialing map[discover.NodeID]connFlag
  43. lookupBuf []*discover.Node // current discovery lookup results
  44. randomNodes []*discover.Node // filled from Table
  45. static map[discover.NodeID]*discover.Node
  46. hist *dialHistory
  47. }
  48. type discoverTable interface {
  49. Self() *discover.Node
  50. Close()
  51. Lookup(target discover.NodeID) []*discover.Node
  52. ReadRandomNodes([]*discover.Node) int
  53. }
  54. // the dial history remembers recent dials.
  55. type dialHistory []pastDial
  56. // pastDial is an entry in the dial history.
  57. type pastDial struct {
  58. id discover.NodeID
  59. exp time.Time
  60. }
  61. type task interface {
  62. Do(*Server)
  63. }
  64. // A dialTask is generated for each node that is dialed.
  65. type dialTask struct {
  66. flags connFlag
  67. dest *discover.Node
  68. }
  69. // discoverTask runs discovery table operations.
  70. // Only one discoverTask is active at any time.
  71. // discoverTask.Do performs a random lookup.
  72. type discoverTask struct {
  73. results []*discover.Node
  74. }
  75. // A waitExpireTask is generated if there are no other tasks
  76. // to keep the loop in Server.run ticking.
  77. type waitExpireTask struct {
  78. time.Duration
  79. }
  80. func newDialState(static []*discover.Node, ntab discoverTable, maxdyn int) *dialstate {
  81. s := &dialstate{
  82. maxDynDials: maxdyn,
  83. ntab: ntab,
  84. static: make(map[discover.NodeID]*discover.Node),
  85. dialing: make(map[discover.NodeID]connFlag),
  86. randomNodes: make([]*discover.Node, maxdyn/2),
  87. hist: new(dialHistory),
  88. }
  89. for _, n := range static {
  90. s.static[n.ID] = n
  91. }
  92. return s
  93. }
  94. func (s *dialstate) addStatic(n *discover.Node) {
  95. s.static[n.ID] = n
  96. }
  97. func (s *dialstate) newTasks(nRunning int, peers map[discover.NodeID]*Peer, now time.Time) []task {
  98. var newtasks []task
  99. addDial := func(flag connFlag, n *discover.Node) bool {
  100. _, dialing := s.dialing[n.ID]
  101. if dialing || peers[n.ID] != nil || s.hist.contains(n.ID) {
  102. return false
  103. }
  104. s.dialing[n.ID] = flag
  105. newtasks = append(newtasks, &dialTask{flags: flag, dest: n})
  106. return true
  107. }
  108. // Compute number of dynamic dials necessary at this point.
  109. needDynDials := s.maxDynDials
  110. for _, p := range peers {
  111. if p.rw.is(dynDialedConn) {
  112. needDynDials--
  113. }
  114. }
  115. for _, flag := range s.dialing {
  116. if flag&dynDialedConn != 0 {
  117. needDynDials--
  118. }
  119. }
  120. // Expire the dial history on every invocation.
  121. s.hist.expire(now)
  122. // Create dials for static nodes if they are not connected.
  123. for _, n := range s.static {
  124. addDial(staticDialedConn, n)
  125. }
  126. // Use random nodes from the table for half of the necessary
  127. // dynamic dials.
  128. randomCandidates := needDynDials / 2
  129. if randomCandidates > 0 {
  130. n := s.ntab.ReadRandomNodes(s.randomNodes)
  131. for i := 0; i < randomCandidates && i < n; i++ {
  132. if addDial(dynDialedConn, s.randomNodes[i]) {
  133. needDynDials--
  134. }
  135. }
  136. }
  137. // Create dynamic dials from random lookup results, removing tried
  138. // items from the result buffer.
  139. i := 0
  140. for ; i < len(s.lookupBuf) && needDynDials > 0; i++ {
  141. if addDial(dynDialedConn, s.lookupBuf[i]) {
  142. needDynDials--
  143. }
  144. }
  145. s.lookupBuf = s.lookupBuf[:copy(s.lookupBuf, s.lookupBuf[i:])]
  146. // Launch a discovery lookup if more candidates are needed.
  147. if len(s.lookupBuf) < needDynDials && !s.lookupRunning {
  148. s.lookupRunning = true
  149. newtasks = append(newtasks, &discoverTask{})
  150. }
  151. // Launch a timer to wait for the next node to expire if all
  152. // candidates have been tried and no task is currently active.
  153. // This should prevent cases where the dialer logic is not ticked
  154. // because there are no pending events.
  155. if nRunning == 0 && len(newtasks) == 0 && s.hist.Len() > 0 {
  156. t := &waitExpireTask{s.hist.min().exp.Sub(now)}
  157. newtasks = append(newtasks, t)
  158. }
  159. return newtasks
  160. }
  161. func (s *dialstate) taskDone(t task, now time.Time) {
  162. switch t := t.(type) {
  163. case *dialTask:
  164. s.hist.add(t.dest.ID, now.Add(dialHistoryExpiration))
  165. delete(s.dialing, t.dest.ID)
  166. case *discoverTask:
  167. s.lookupRunning = false
  168. s.lookupBuf = append(s.lookupBuf, t.results...)
  169. }
  170. }
  171. func (t *dialTask) Do(srv *Server) {
  172. addr := &net.TCPAddr{IP: t.dest.IP, Port: int(t.dest.TCP)}
  173. glog.V(logger.Debug).Infof("dialing %v\n", t.dest)
  174. fd, err := srv.Dialer.Dial("tcp", addr.String())
  175. if err != nil {
  176. glog.V(logger.Detail).Infof("dial error: %v", err)
  177. return
  178. }
  179. mfd := newMeteredConn(fd, false)
  180. srv.setupConn(mfd, t.flags, t.dest)
  181. }
  182. func (t *dialTask) String() string {
  183. return fmt.Sprintf("%v %x %v:%d", t.flags, t.dest.ID[:8], t.dest.IP, t.dest.TCP)
  184. }
  185. func (t *discoverTask) Do(srv *Server) {
  186. // newTasks generates a lookup task whenever dynamic dials are
  187. // necessary. Lookups need to take some time, otherwise the
  188. // event loop spins too fast.
  189. next := srv.lastLookup.Add(lookupInterval)
  190. if now := time.Now(); now.Before(next) {
  191. time.Sleep(next.Sub(now))
  192. }
  193. srv.lastLookup = time.Now()
  194. var target discover.NodeID
  195. rand.Read(target[:])
  196. t.results = srv.ntab.Lookup(target)
  197. }
  198. func (t *discoverTask) String() string {
  199. s := "discovery lookup"
  200. if len(t.results) > 0 {
  201. s += fmt.Sprintf(" (%d results)", len(t.results))
  202. }
  203. return s
  204. }
  205. func (t waitExpireTask) Do(*Server) {
  206. time.Sleep(t.Duration)
  207. }
  208. func (t waitExpireTask) String() string {
  209. return fmt.Sprintf("wait for dial hist expire (%v)", t.Duration)
  210. }
  211. // Use only these methods to access or modify dialHistory.
  212. func (h dialHistory) min() pastDial {
  213. return h[0]
  214. }
  215. func (h *dialHistory) add(id discover.NodeID, exp time.Time) {
  216. heap.Push(h, pastDial{id, exp})
  217. }
  218. func (h dialHistory) contains(id discover.NodeID) bool {
  219. for _, v := range h {
  220. if v.id == id {
  221. return true
  222. }
  223. }
  224. return false
  225. }
  226. func (h *dialHistory) expire(now time.Time) {
  227. for h.Len() > 0 && h.min().exp.Before(now) {
  228. heap.Pop(h)
  229. }
  230. }
  231. // heap.Interface boilerplate
  232. func (h dialHistory) Len() int { return len(h) }
  233. func (h dialHistory) Less(i, j int) bool { return h[i].exp.Before(h[j].exp) }
  234. func (h dialHistory) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  235. func (h *dialHistory) Push(x interface{}) {
  236. *h = append(*h, x.(pastDial))
  237. }
  238. func (h *dialHistory) Pop() interface{} {
  239. old := *h
  240. n := len(old)
  241. x := old[n-1]
  242. *h = old[0 : n-1]
  243. return x
  244. }