control.go 14 KB

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