dial.go 7.9 KB

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