control.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // Copyright 2016 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 flowcontrol implements a client side flow control mechanism
  17. package flowcontrol
  18. import (
  19. "fmt"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common/mclock"
  23. "github.com/ethereum/go-ethereum/log"
  24. )
  25. const (
  26. // fcTimeConst is the time constant applied for MinRecharge during linear
  27. // buffer recharge period
  28. fcTimeConst = time.Millisecond
  29. // DecParamDelay is applied at server side when decreasing capacity in order to
  30. // avoid a buffer underrun error due to requests sent by the client before
  31. // receiving the capacity update announcement
  32. DecParamDelay = time.Second * 2
  33. // keepLogs is the duration of keeping logs; logging is not used if zero
  34. keepLogs = 0
  35. )
  36. // ServerParams are the flow control parameters specified by a server for a client
  37. //
  38. // Note: a server can assign different amounts of capacity to each client by giving
  39. // different parameters to them.
  40. type ServerParams struct {
  41. BufLimit, MinRecharge uint64
  42. }
  43. // scheduledUpdate represents a delayed flow control parameter update
  44. type scheduledUpdate struct {
  45. time mclock.AbsTime
  46. params ServerParams
  47. }
  48. // ClientNode is the flow control system's representation of a client
  49. // (used in server mode only)
  50. type ClientNode struct {
  51. params ServerParams
  52. bufValue uint64
  53. lastTime mclock.AbsTime
  54. updateSchedule []scheduledUpdate
  55. sumCost uint64 // sum of req costs received from this client
  56. accepted map[uint64]uint64 // value = sumCost after accepting the given req
  57. lock sync.Mutex
  58. cm *ClientManager
  59. log *logger
  60. cmNodeFields
  61. }
  62. // NewClientNode returns a new ClientNode
  63. func NewClientNode(cm *ClientManager, params ServerParams) *ClientNode {
  64. node := &ClientNode{
  65. cm: cm,
  66. params: params,
  67. bufValue: params.BufLimit,
  68. lastTime: cm.clock.Now(),
  69. accepted: make(map[uint64]uint64),
  70. }
  71. if keepLogs > 0 {
  72. node.log = newLogger(keepLogs)
  73. }
  74. cm.connect(node)
  75. return node
  76. }
  77. // Disconnect should be called when a client is disconnected
  78. func (node *ClientNode) Disconnect() {
  79. node.cm.disconnect(node)
  80. }
  81. // update recalculates the buffer value at a specified time while also performing
  82. // scheduled flow control parameter updates if necessary
  83. func (node *ClientNode) update(now mclock.AbsTime) {
  84. for len(node.updateSchedule) > 0 && node.updateSchedule[0].time <= now {
  85. node.recalcBV(node.updateSchedule[0].time)
  86. node.updateParams(node.updateSchedule[0].params, now)
  87. node.updateSchedule = node.updateSchedule[1:]
  88. }
  89. node.recalcBV(now)
  90. }
  91. // recalcBV recalculates the buffer value at a specified time
  92. func (node *ClientNode) recalcBV(now mclock.AbsTime) {
  93. dt := uint64(now - node.lastTime)
  94. if now < node.lastTime {
  95. dt = 0
  96. }
  97. node.bufValue += node.params.MinRecharge * dt / uint64(fcTimeConst)
  98. if node.bufValue > node.params.BufLimit {
  99. node.bufValue = node.params.BufLimit
  100. }
  101. if node.log != nil {
  102. node.log.add(now, fmt.Sprintf("updated bv=%d MRR=%d BufLimit=%d", node.bufValue, node.params.MinRecharge, node.params.BufLimit))
  103. }
  104. node.lastTime = now
  105. }
  106. // UpdateParams updates the flow control parameters of a client node
  107. func (node *ClientNode) UpdateParams(params ServerParams) {
  108. node.lock.Lock()
  109. defer node.lock.Unlock()
  110. now := node.cm.clock.Now()
  111. node.update(now)
  112. if params.MinRecharge >= node.params.MinRecharge {
  113. node.updateSchedule = nil
  114. node.updateParams(params, now)
  115. } else {
  116. for i, s := range node.updateSchedule {
  117. if params.MinRecharge >= s.params.MinRecharge {
  118. s.params = params
  119. node.updateSchedule = node.updateSchedule[:i+1]
  120. return
  121. }
  122. }
  123. node.updateSchedule = append(node.updateSchedule, scheduledUpdate{time: now + mclock.AbsTime(DecParamDelay), params: params})
  124. }
  125. }
  126. // updateParams updates the flow control parameters of the node
  127. func (node *ClientNode) updateParams(params ServerParams, now mclock.AbsTime) {
  128. diff := params.BufLimit - node.params.BufLimit
  129. if int64(diff) > 0 {
  130. node.bufValue += diff
  131. } else if node.bufValue > params.BufLimit {
  132. node.bufValue = params.BufLimit
  133. }
  134. node.cm.updateParams(node, params, now)
  135. }
  136. // AcceptRequest returns whether a new request can be accepted and the missing
  137. // buffer amount if it was rejected due to a buffer underrun. If accepted, maxCost
  138. // is deducted from the flow control buffer.
  139. func (node *ClientNode) AcceptRequest(reqID, index, maxCost uint64) (accepted bool, bufShort uint64, priority int64) {
  140. node.lock.Lock()
  141. defer node.lock.Unlock()
  142. now := node.cm.clock.Now()
  143. node.update(now)
  144. if maxCost > node.bufValue {
  145. if node.log != nil {
  146. node.log.add(now, fmt.Sprintf("rejected reqID=%d bv=%d maxCost=%d", reqID, node.bufValue, maxCost))
  147. node.log.dump(now)
  148. }
  149. return false, maxCost - node.bufValue, 0
  150. }
  151. node.bufValue -= maxCost
  152. node.sumCost += maxCost
  153. if node.log != nil {
  154. node.log.add(now, fmt.Sprintf("accepted reqID=%d bv=%d maxCost=%d sumCost=%d", reqID, node.bufValue, maxCost, node.sumCost))
  155. }
  156. node.accepted[index] = node.sumCost
  157. return true, 0, node.cm.accepted(node, maxCost, now)
  158. }
  159. // RequestProcessed should be called when the request has been processed
  160. func (node *ClientNode) RequestProcessed(reqID, index, maxCost, realCost uint64) (bv uint64) {
  161. node.lock.Lock()
  162. defer node.lock.Unlock()
  163. now := node.cm.clock.Now()
  164. node.update(now)
  165. node.cm.processed(node, maxCost, realCost, now)
  166. bv = node.bufValue + node.sumCost - node.accepted[index]
  167. if node.log != nil {
  168. node.log.add(now, fmt.Sprintf("processed reqID=%d bv=%d maxCost=%d realCost=%d sumCost=%d oldSumCost=%d reportedBV=%d", reqID, node.bufValue, maxCost, realCost, node.sumCost, node.accepted[index], bv))
  169. }
  170. delete(node.accepted, index)
  171. return
  172. }
  173. // ServerNode is the flow control system's representation of a server
  174. // (used in client mode only)
  175. type ServerNode struct {
  176. clock mclock.Clock
  177. bufEstimate uint64
  178. bufRecharge bool
  179. lastTime mclock.AbsTime
  180. params ServerParams
  181. sumCost uint64 // sum of req costs sent to this server
  182. pending map[uint64]uint64 // value = sumCost after sending the given req
  183. log *logger
  184. lock sync.RWMutex
  185. }
  186. // NewServerNode returns a new ServerNode
  187. func NewServerNode(params ServerParams, clock mclock.Clock) *ServerNode {
  188. node := &ServerNode{
  189. clock: clock,
  190. bufEstimate: params.BufLimit,
  191. bufRecharge: false,
  192. lastTime: clock.Now(),
  193. params: params,
  194. pending: make(map[uint64]uint64),
  195. }
  196. if keepLogs > 0 {
  197. node.log = newLogger(keepLogs)
  198. }
  199. return node
  200. }
  201. // UpdateParams updates the flow control parameters of the node
  202. func (node *ServerNode) UpdateParams(params ServerParams) {
  203. node.lock.Lock()
  204. defer node.lock.Unlock()
  205. node.recalcBLE(mclock.Now())
  206. if params.BufLimit > node.params.BufLimit {
  207. node.bufEstimate += params.BufLimit - node.params.BufLimit
  208. } else {
  209. if node.bufEstimate > params.BufLimit {
  210. node.bufEstimate = params.BufLimit
  211. }
  212. }
  213. node.params = params
  214. }
  215. // recalcBLE recalculates the lowest estimate for the client's buffer value at
  216. // the given server at the specified time
  217. func (node *ServerNode) recalcBLE(now mclock.AbsTime) {
  218. if now < node.lastTime {
  219. return
  220. }
  221. if node.bufRecharge {
  222. dt := uint64(now - node.lastTime)
  223. node.bufEstimate += node.params.MinRecharge * dt / uint64(fcTimeConst)
  224. if node.bufEstimate >= node.params.BufLimit {
  225. node.bufEstimate = node.params.BufLimit
  226. node.bufRecharge = false
  227. }
  228. }
  229. node.lastTime = now
  230. if node.log != nil {
  231. node.log.add(now, fmt.Sprintf("updated bufEst=%d MRR=%d BufLimit=%d", node.bufEstimate, node.params.MinRecharge, node.params.BufLimit))
  232. }
  233. }
  234. // safetyMargin is added to the flow control waiting time when estimated buffer value is low
  235. const safetyMargin = time.Millisecond
  236. // CanSend returns the minimum waiting time required before sending a request
  237. // with the given maximum estimated cost. Second return value is the relative
  238. // estimated buffer level after sending the request (divided by BufLimit).
  239. func (node *ServerNode) CanSend(maxCost uint64) (time.Duration, float64) {
  240. node.lock.RLock()
  241. defer node.lock.RUnlock()
  242. now := node.clock.Now()
  243. node.recalcBLE(now)
  244. maxCost += uint64(safetyMargin) * node.params.MinRecharge / uint64(fcTimeConst)
  245. if maxCost > node.params.BufLimit {
  246. maxCost = node.params.BufLimit
  247. }
  248. if node.bufEstimate >= maxCost {
  249. relBuf := float64(node.bufEstimate-maxCost) / float64(node.params.BufLimit)
  250. if node.log != nil {
  251. node.log.add(now, fmt.Sprintf("canSend bufEst=%d maxCost=%d true relBuf=%f", node.bufEstimate, maxCost, relBuf))
  252. }
  253. return 0, relBuf
  254. }
  255. timeLeft := time.Duration((maxCost - node.bufEstimate) * uint64(fcTimeConst) / node.params.MinRecharge)
  256. if node.log != nil {
  257. node.log.add(now, fmt.Sprintf("canSend bufEst=%d maxCost=%d false timeLeft=%v", node.bufEstimate, maxCost, timeLeft))
  258. }
  259. return timeLeft, 0
  260. }
  261. // QueuedRequest should be called when the request has been assigned to the given
  262. // server node, before putting it in the send queue. It is mandatory that requests
  263. // are sent in the same order as the QueuedRequest calls are made.
  264. func (node *ServerNode) QueuedRequest(reqID, maxCost uint64) {
  265. node.lock.Lock()
  266. defer node.lock.Unlock()
  267. now := node.clock.Now()
  268. node.recalcBLE(now)
  269. // Note: we do not know when requests actually arrive to the server so bufRecharge
  270. // is not turned on here if buffer was full; in this case it is going to be turned
  271. // on by the first reply's bufValue feedback
  272. if node.bufEstimate >= maxCost {
  273. node.bufEstimate -= maxCost
  274. } else {
  275. log.Error("Queued request with insufficient buffer estimate")
  276. node.bufEstimate = 0
  277. }
  278. node.sumCost += maxCost
  279. node.pending[reqID] = node.sumCost
  280. if node.log != nil {
  281. node.log.add(now, fmt.Sprintf("queued reqID=%d bufEst=%d maxCost=%d sumCost=%d", reqID, node.bufEstimate, maxCost, node.sumCost))
  282. }
  283. }
  284. // ReceivedReply adjusts estimated buffer value according to the value included in
  285. // the latest request reply.
  286. func (node *ServerNode) ReceivedReply(reqID, bv uint64) {
  287. node.lock.Lock()
  288. defer node.lock.Unlock()
  289. now := node.clock.Now()
  290. node.recalcBLE(now)
  291. if bv > node.params.BufLimit {
  292. bv = node.params.BufLimit
  293. }
  294. sc, ok := node.pending[reqID]
  295. if !ok {
  296. return
  297. }
  298. delete(node.pending, reqID)
  299. cc := node.sumCost - sc
  300. newEstimate := uint64(0)
  301. if bv > cc {
  302. newEstimate = bv - cc
  303. }
  304. if newEstimate > node.bufEstimate {
  305. // Note: we never reduce the buffer estimate based on the reported value because
  306. // this can only happen because of the delayed delivery of the latest reply.
  307. // The lowest estimate based on the previous reply can still be considered valid.
  308. node.bufEstimate = newEstimate
  309. }
  310. node.bufRecharge = node.bufEstimate < node.params.BufLimit
  311. node.lastTime = now
  312. if node.log != nil {
  313. node.log.add(now, fmt.Sprintf("received reqID=%d bufEst=%d reportedBv=%d sumCost=%d oldSumCost=%d", reqID, node.bufEstimate, bv, node.sumCost, sc))
  314. }
  315. }
  316. // DumpLogs dumps the event log if logging is used
  317. func (node *ServerNode) DumpLogs() {
  318. node.lock.Lock()
  319. defer node.lock.Unlock()
  320. if node.log != nil {
  321. node.log.dump(node.clock.Now())
  322. }
  323. }