dial.go 7.8 KB

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