control.go 14 KB

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