clientpool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. // Copyright 2019 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 les
  17. import (
  18. "fmt"
  19. "sync"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common/mclock"
  22. "github.com/ethereum/go-ethereum/ethdb"
  23. "github.com/ethereum/go-ethereum/les/utils"
  24. vfs "github.com/ethereum/go-ethereum/les/vflux/server"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/p2p/enode"
  27. "github.com/ethereum/go-ethereum/p2p/enr"
  28. "github.com/ethereum/go-ethereum/p2p/nodestate"
  29. )
  30. const (
  31. defaultNegExpTC = 3600 // default time constant (in seconds) for exponentially reducing negative balance
  32. // defaultConnectedBias is applied to already connected clients So that
  33. // already connected client won't be kicked out very soon and we
  34. // can ensure all connected clients can have enough time to request
  35. // or sync some data.
  36. //
  37. // todo(rjl493456442) make it configurable. It can be the option of
  38. // free trial time!
  39. defaultConnectedBias = time.Minute * 3
  40. inactiveTimeout = time.Second * 10
  41. )
  42. // clientPool implements a client database that assigns a priority to each client
  43. // based on a positive and negative balance. Positive balance is externally assigned
  44. // to prioritized clients and is decreased with connection time and processed
  45. // requests (unless the price factors are zero). If the positive balance is zero
  46. // then negative balance is accumulated.
  47. //
  48. // Balance tracking and priority calculation for connected clients is done by
  49. // balanceTracker. activeQueue ensures that clients with the lowest positive or
  50. // highest negative balance get evicted when the total capacity allowance is full
  51. // and new clients with a better balance want to connect.
  52. //
  53. // Already connected nodes receive a small bias in their favor in order to avoid
  54. // accepting and instantly kicking out clients. In theory, we try to ensure that
  55. // each client can have several minutes of connection time.
  56. //
  57. // Balances of disconnected clients are stored in nodeDB including positive balance
  58. // and negative banalce. Boeth positive balance and negative balance will decrease
  59. // exponentially. If the balance is low enough, then the record will be dropped.
  60. type clientPool struct {
  61. vfs.BalanceTrackerSetup
  62. vfs.PriorityPoolSetup
  63. lock sync.Mutex
  64. clock mclock.Clock
  65. closed bool
  66. removePeer func(enode.ID)
  67. ns *nodestate.NodeStateMachine
  68. pp *vfs.PriorityPool
  69. bt *vfs.BalanceTracker
  70. defaultPosFactors, defaultNegFactors vfs.PriceFactors
  71. posExpTC, negExpTC uint64
  72. minCap uint64 // The minimal capacity value allowed for any client
  73. connectedBias time.Duration
  74. capLimit uint64
  75. }
  76. // clientPoolPeer represents a client peer in the pool.
  77. // Positive balances are assigned to node key while negative balances are assigned
  78. // to freeClientId. Currently network IP address without port is used because
  79. // clients have a limited access to IP addresses while new node keys can be easily
  80. // generated so it would be useless to assign a negative value to them.
  81. type clientPoolPeer interface {
  82. Node() *enode.Node
  83. freeClientId() string
  84. updateCapacity(uint64)
  85. freeze()
  86. allowInactive() bool
  87. }
  88. // clientInfo defines all information required by clientpool.
  89. type clientInfo struct {
  90. node *enode.Node
  91. address string
  92. peer clientPoolPeer
  93. connected, priority bool
  94. connectedAt mclock.AbsTime
  95. balance *vfs.NodeBalance
  96. }
  97. // newClientPool creates a new client pool
  98. func newClientPool(ns *nodestate.NodeStateMachine, lespayDb ethdb.Database, minCap uint64, connectedBias time.Duration, clock mclock.Clock, removePeer func(enode.ID)) *clientPool {
  99. pool := &clientPool{
  100. ns: ns,
  101. BalanceTrackerSetup: balanceTrackerSetup,
  102. PriorityPoolSetup: priorityPoolSetup,
  103. clock: clock,
  104. minCap: minCap,
  105. connectedBias: connectedBias,
  106. removePeer: removePeer,
  107. }
  108. pool.bt = vfs.NewBalanceTracker(ns, balanceTrackerSetup, lespayDb, clock, &utils.Expirer{}, &utils.Expirer{})
  109. pool.pp = vfs.NewPriorityPool(ns, priorityPoolSetup, clock, minCap, connectedBias, 4)
  110. // set default expiration constants used by tests
  111. // Note: server overwrites this if token sale is active
  112. pool.bt.SetExpirationTCs(0, defaultNegExpTC)
  113. ns.SubscribeState(pool.InactiveFlag.Or(pool.PriorityFlag), func(node *enode.Node, oldState, newState nodestate.Flags) {
  114. if newState.Equals(pool.InactiveFlag) {
  115. ns.AddTimeout(node, pool.InactiveFlag, inactiveTimeout)
  116. }
  117. if oldState.Equals(pool.InactiveFlag) && newState.Equals(pool.InactiveFlag.Or(pool.PriorityFlag)) {
  118. ns.SetStateSub(node, pool.InactiveFlag, nodestate.Flags{}, 0) // remove timeout
  119. }
  120. })
  121. ns.SubscribeState(pool.ActiveFlag.Or(pool.PriorityFlag), func(node *enode.Node, oldState, newState nodestate.Flags) {
  122. c, _ := ns.GetField(node, clientInfoField).(*clientInfo)
  123. if c == nil {
  124. return
  125. }
  126. c.priority = newState.HasAll(pool.PriorityFlag)
  127. if newState.Equals(pool.ActiveFlag) {
  128. cap, _ := ns.GetField(node, pool.CapacityField).(uint64)
  129. if cap > minCap {
  130. pool.pp.RequestCapacity(node, minCap, 0, true)
  131. }
  132. }
  133. })
  134. ns.SubscribeState(pool.InactiveFlag.Or(pool.ActiveFlag), func(node *enode.Node, oldState, newState nodestate.Flags) {
  135. if oldState.IsEmpty() {
  136. clientConnectedMeter.Mark(1)
  137. log.Debug("Client connected", "id", node.ID())
  138. }
  139. if oldState.Equals(pool.InactiveFlag) && newState.Equals(pool.ActiveFlag) {
  140. clientActivatedMeter.Mark(1)
  141. log.Debug("Client activated", "id", node.ID())
  142. }
  143. if oldState.Equals(pool.ActiveFlag) && newState.Equals(pool.InactiveFlag) {
  144. clientDeactivatedMeter.Mark(1)
  145. log.Debug("Client deactivated", "id", node.ID())
  146. c, _ := ns.GetField(node, clientInfoField).(*clientInfo)
  147. if c == nil || !c.peer.allowInactive() {
  148. pool.removePeer(node.ID())
  149. }
  150. }
  151. if newState.IsEmpty() {
  152. clientDisconnectedMeter.Mark(1)
  153. log.Debug("Client disconnected", "id", node.ID())
  154. pool.removePeer(node.ID())
  155. }
  156. })
  157. var totalConnected uint64
  158. ns.SubscribeField(pool.CapacityField, func(node *enode.Node, state nodestate.Flags, oldValue, newValue interface{}) {
  159. oldCap, _ := oldValue.(uint64)
  160. newCap, _ := newValue.(uint64)
  161. totalConnected += newCap - oldCap
  162. totalConnectedGauge.Update(int64(totalConnected))
  163. c, _ := ns.GetField(node, clientInfoField).(*clientInfo)
  164. if c != nil {
  165. c.peer.updateCapacity(newCap)
  166. }
  167. })
  168. return pool
  169. }
  170. // stop shuts the client pool down
  171. func (f *clientPool) stop() {
  172. f.lock.Lock()
  173. f.closed = true
  174. f.lock.Unlock()
  175. f.ns.ForEach(nodestate.Flags{}, nodestate.Flags{}, func(node *enode.Node, state nodestate.Flags) {
  176. // enforces saving all balances in BalanceTracker
  177. f.disconnectNode(node)
  178. })
  179. f.bt.Stop()
  180. }
  181. // connect should be called after a successful handshake. If the connection was
  182. // rejected, there is no need to call disconnect.
  183. func (f *clientPool) connect(peer clientPoolPeer) (uint64, error) {
  184. f.lock.Lock()
  185. defer f.lock.Unlock()
  186. // Short circuit if clientPool is already closed.
  187. if f.closed {
  188. return 0, fmt.Errorf("Client pool is already closed")
  189. }
  190. // Dedup connected peers.
  191. node, freeID := peer.Node(), peer.freeClientId()
  192. if f.ns.GetField(node, clientInfoField) != nil {
  193. log.Debug("Client already connected", "address", freeID, "id", node.ID().String())
  194. return 0, fmt.Errorf("Client already connected address=%s id=%s", freeID, node.ID().String())
  195. }
  196. now := f.clock.Now()
  197. c := &clientInfo{
  198. node: node,
  199. address: freeID,
  200. peer: peer,
  201. connected: true,
  202. connectedAt: now,
  203. }
  204. f.ns.SetField(node, clientInfoField, c)
  205. f.ns.SetField(node, connAddressField, freeID)
  206. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance == nil {
  207. f.disconnect(peer)
  208. return 0, nil
  209. }
  210. c.balance.SetPriceFactors(f.defaultPosFactors, f.defaultNegFactors)
  211. f.ns.SetState(node, f.InactiveFlag, nodestate.Flags{}, 0)
  212. var allowed bool
  213. f.ns.Operation(func() {
  214. _, allowed = f.pp.RequestCapacity(node, f.minCap, f.connectedBias, true)
  215. })
  216. if allowed {
  217. return f.minCap, nil
  218. }
  219. if !peer.allowInactive() {
  220. f.disconnect(peer)
  221. }
  222. return 0, nil
  223. }
  224. // setConnectedBias sets the connection bias, which is applied to already connected clients
  225. // So that already connected client won't be kicked out very soon and we can ensure all
  226. // connected clients can have enough time to request or sync some data.
  227. func (f *clientPool) setConnectedBias(bias time.Duration) {
  228. f.lock.Lock()
  229. defer f.lock.Unlock()
  230. f.connectedBias = bias
  231. f.pp.SetActiveBias(bias)
  232. }
  233. // disconnect should be called when a connection is terminated. If the disconnection
  234. // was initiated by the pool itself using disconnectFn then calling disconnect is
  235. // not necessary but permitted.
  236. func (f *clientPool) disconnect(p clientPoolPeer) {
  237. f.disconnectNode(p.Node())
  238. }
  239. // disconnectNode removes node fields and flags related to connected status
  240. func (f *clientPool) disconnectNode(node *enode.Node) {
  241. f.ns.SetField(node, connAddressField, nil)
  242. f.ns.SetField(node, clientInfoField, nil)
  243. }
  244. // setDefaultFactors sets the default price factors applied to subsequently connected clients
  245. func (f *clientPool) setDefaultFactors(posFactors, negFactors vfs.PriceFactors) {
  246. f.lock.Lock()
  247. defer f.lock.Unlock()
  248. f.defaultPosFactors = posFactors
  249. f.defaultNegFactors = negFactors
  250. }
  251. // capacityInfo returns the total capacity allowance, the total capacity of connected
  252. // clients and the total capacity of connected and prioritized clients
  253. func (f *clientPool) capacityInfo() (uint64, uint64, uint64) {
  254. f.lock.Lock()
  255. defer f.lock.Unlock()
  256. // total priority active cap will be supported when the token issuer module is added
  257. _, activeCap := f.pp.Active()
  258. return f.capLimit, activeCap, 0
  259. }
  260. // setLimits sets the maximum number and total capacity of connected clients,
  261. // dropping some of them if necessary.
  262. func (f *clientPool) setLimits(totalConn int, totalCap uint64) {
  263. f.lock.Lock()
  264. defer f.lock.Unlock()
  265. f.capLimit = totalCap
  266. f.pp.SetLimits(uint64(totalConn), totalCap)
  267. }
  268. // setCapacity sets the assigned capacity of a connected client
  269. func (f *clientPool) setCapacity(node *enode.Node, freeID string, capacity uint64, bias time.Duration, setCap bool) (uint64, error) {
  270. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  271. if c == nil {
  272. if setCap {
  273. return 0, fmt.Errorf("client %064x is not connected", node.ID())
  274. }
  275. c = &clientInfo{node: node}
  276. f.ns.SetField(node, clientInfoField, c)
  277. f.ns.SetField(node, connAddressField, freeID)
  278. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance == nil {
  279. log.Error("BalanceField is missing", "node", node.ID())
  280. return 0, fmt.Errorf("BalanceField of %064x is missing", node.ID())
  281. }
  282. defer func() {
  283. f.ns.SetField(node, connAddressField, nil)
  284. f.ns.SetField(node, clientInfoField, nil)
  285. }()
  286. }
  287. var (
  288. minPriority int64
  289. allowed bool
  290. )
  291. f.ns.Operation(func() {
  292. if !setCap || c.priority {
  293. // check clientInfo.priority inside Operation to ensure thread safety
  294. minPriority, allowed = f.pp.RequestCapacity(node, capacity, bias, setCap)
  295. }
  296. })
  297. if allowed {
  298. return 0, nil
  299. }
  300. missing := c.balance.PosBalanceMissing(minPriority, capacity, bias)
  301. if missing < 1 {
  302. // ensure that we never return 0 missing and insufficient priority error
  303. missing = 1
  304. }
  305. return missing, errNoPriority
  306. }
  307. // setCapacityLocked is the equivalent of setCapacity used when f.lock is already locked
  308. func (f *clientPool) setCapacityLocked(node *enode.Node, freeID string, capacity uint64, minConnTime time.Duration, setCap bool) (uint64, error) {
  309. f.lock.Lock()
  310. defer f.lock.Unlock()
  311. return f.setCapacity(node, freeID, capacity, minConnTime, setCap)
  312. }
  313. // forClients calls the supplied callback for either the listed node IDs or all connected
  314. // nodes. It passes a valid clientInfo to the callback and ensures that the necessary
  315. // fields and flags are set in order for BalanceTracker and PriorityPool to work even if
  316. // the node is not connected.
  317. func (f *clientPool) forClients(ids []enode.ID, cb func(client *clientInfo)) {
  318. f.lock.Lock()
  319. defer f.lock.Unlock()
  320. if len(ids) == 0 {
  321. f.ns.ForEach(nodestate.Flags{}, nodestate.Flags{}, func(node *enode.Node, state nodestate.Flags) {
  322. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  323. if c != nil {
  324. cb(c)
  325. }
  326. })
  327. } else {
  328. for _, id := range ids {
  329. node := f.ns.GetNode(id)
  330. if node == nil {
  331. node = enode.SignNull(&enr.Record{}, id)
  332. }
  333. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  334. if c != nil {
  335. cb(c)
  336. } else {
  337. c = &clientInfo{node: node}
  338. f.ns.SetField(node, clientInfoField, c)
  339. f.ns.SetField(node, connAddressField, "")
  340. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance != nil {
  341. cb(c)
  342. } else {
  343. log.Error("BalanceField is missing")
  344. }
  345. f.ns.SetField(node, connAddressField, nil)
  346. f.ns.SetField(node, clientInfoField, nil)
  347. }
  348. }
  349. }
  350. }