dial.go 7.1 KB

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