Skip to content

Commit 4996fce

Browse files
les, les/lespay/server: refactor client pool (#21236)
* les, les/lespay/server: refactor client pool * les: use ns.Operation and sub calls where needed * les: fixed tests * les: removed active/inactive logic from peerSet * les: removed active/inactive peer logic * les: fixed linter warnings * les: fixed more linter errors and added missing metrics * les: addressed comments * cmd/geth: fixed TestPriorityClient * les: simplified clientPool state machine * les/lespay/server: do not use goroutine for balance callbacks * internal/web3ext: fix addBalance required parameters * les: removed freeCapacity, always connect at minCapacity initially * les: only allow capacity change with priority status Co-authored-by: rjl493456442 <garyrong0905@gmail.com>
1 parent f7112cc commit 4996fce

24 files changed

Lines changed: 3100 additions & 1692 deletions

‎cmd/geth/les_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ func TestPriorityClient(t *testing.T) {
152152
defer prioCli.killAndWait()
153153
// 3_000_000_000 once we move to Go 1.13
154154
tokens := 3000000000
155-
lightServer.callRPC(nil, "les_addBalance", prioCli.getNodeInfo().ID, tokens, "foobar")
155+
lightServer.callRPC(nil, "les_addBalance", prioCli.getNodeInfo().ID, tokens)
156156
prioCli.addPeer(lightServer)
157157

158158
// Check if priority client is actually syncing and the regular client got kicked out

‎common/prque/lazyqueue.go‎

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,15 @@ type LazyQueue struct {
3636
// Items are stored in one of two internal queues ordered by estimated max
3737
// priority until the next and the next-after-next refresh. Update and Refresh
3838
// always places items in queue[1].
39-
queue [2]*sstack
40-
popQueue *sstack
41-
period time.Duration
42-
maxUntil mclock.AbsTime
43-
indexOffset int
44-
setIndex SetIndexCallback
45-
priority PriorityCallback
46-
maxPriority MaxPriorityCallback
39+
queue [2]*sstack
40+
popQueue *sstack
41+
period time.Duration
42+
maxUntil mclock.AbsTime
43+
indexOffset int
44+
setIndex SetIndexCallback
45+
priority PriorityCallback
46+
maxPriority MaxPriorityCallback
47+
lastRefresh1, lastRefresh2 mclock.AbsTime
4748
}
4849

4950
type (
@@ -54,14 +55,17 @@ type (
5455
// NewLazyQueue creates a new lazy queue
5556
func NewLazyQueue(setIndex SetIndexCallback, priority PriorityCallback, maxPriority MaxPriorityCallback, clock mclock.Clock, refreshPeriod time.Duration) *LazyQueue {
5657
q := &LazyQueue{
57-
popQueue: newSstack(nil),
58-
setIndex: setIndex,
59-
priority: priority,
60-
maxPriority: maxPriority,
61-
clock: clock,
62-
period: refreshPeriod}
58+
popQueue: newSstack(nil),
59+
setIndex: setIndex,
60+
priority: priority,
61+
maxPriority: maxPriority,
62+
clock: clock,
63+
period: refreshPeriod,
64+
lastRefresh1: clock.Now(),
65+
lastRefresh2: clock.Now(),
66+
}
6367
q.Reset()
64-
q.Refresh()
68+
q.refresh(clock.Now())
6569
return q
6670
}
6771

@@ -71,9 +75,19 @@ func (q *LazyQueue) Reset() {
7175
q.queue[1] = newSstack(q.setIndex1)
7276
}
7377

74-
// Refresh should be called at least with the frequency specified by the refreshPeriod parameter
78+
// Refresh performs queue re-evaluation if necessary
7579
func (q *LazyQueue) Refresh() {
76-
q.maxUntil = q.clock.Now() + mclock.AbsTime(q.period)
80+
now := q.clock.Now()
81+
for time.Duration(now-q.lastRefresh2) >= q.period*2 {
82+
q.refresh(now)
83+
q.lastRefresh2 = q.lastRefresh1
84+
q.lastRefresh1 = now
85+
}
86+
}
87+
88+
// refresh re-evaluates items in the older queue and swaps the two queues
89+
func (q *LazyQueue) refresh(now mclock.AbsTime) {
90+
q.maxUntil = now + mclock.AbsTime(q.period)
7791
for q.queue[0].Len() != 0 {
7892
q.Push(heap.Pop(q.queue[0]).(*item).value)
7993
}
@@ -139,6 +153,7 @@ func (q *LazyQueue) MultiPop(callback func(data interface{}, priority int64) boo
139153
}
140154
return
141155
}
156+
nextIndex = q.peekIndex() // re-check because callback is allowed to push items back
142157
}
143158
}
144159
}

‎internal/web3ext/web3ext.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ web3._extend({
844844
new web3._extend.Method({
845845
name: 'addBalance',
846846
call: 'les_addBalance',
847-
params: 3
847+
params: 2
848848
}),
849849
],
850850
properties:

‎les/api.go‎

Lines changed: 53 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,25 @@ package les
1919
import (
2020
"errors"
2121
"fmt"
22-
"math"
2322
"time"
2423

2524
"github.com/ethereum/go-ethereum/common/hexutil"
2625
"github.com/ethereum/go-ethereum/common/mclock"
26+
lps "github.com/ethereum/go-ethereum/les/lespay/server"
2727
"github.com/ethereum/go-ethereum/p2p/enode"
2828
)
2929

3030
var (
3131
errNoCheckpoint = errors.New("no local checkpoint provided")
3232
errNotActivated = errors.New("checkpoint registrar is not activated")
3333
errUnknownBenchmarkType = errors.New("unknown benchmark type")
34-
errBalanceOverflow = errors.New("balance overflow")
3534
errNoPriority = errors.New("priority too low to raise capacity")
3635
)
3736

38-
const maxBalance = math.MaxInt64
39-
4037
// PrivateLightServerAPI provides an API to access the LES light server.
4138
type PrivateLightServerAPI struct {
4239
server *LesServer
43-
defaultPosFactors, defaultNegFactors priceFactors
40+
defaultPosFactors, defaultNegFactors lps.PriceFactors
4441
}
4542

4643
// NewPrivateLightServerAPI creates a new LES light server API.
@@ -57,17 +54,15 @@ func (api *PrivateLightServerAPI) ServerInfo() map[string]interface{} {
5754
res := make(map[string]interface{})
5855
res["minimumCapacity"] = api.server.minCapacity
5956
res["maximumCapacity"] = api.server.maxCapacity
60-
res["freeClientCapacity"] = api.server.freeCapacity
6157
res["totalCapacity"], res["totalConnectedCapacity"], res["priorityConnectedCapacity"] = api.server.clientPool.capacityInfo()
6258
return res
6359
}
6460

6561
// ClientInfo returns information about clients listed in the ids list or matching the given tags
6662
func (api *PrivateLightServerAPI) ClientInfo(ids []enode.ID) map[enode.ID]map[string]interface{} {
6763
res := make(map[enode.ID]map[string]interface{})
68-
api.server.clientPool.forClients(ids, func(client *clientInfo, id enode.ID) error {
69-
res[id] = api.clientInfo(client, id)
70-
return nil
64+
api.server.clientPool.forClients(ids, func(client *clientInfo) {
65+
res[client.node.ID()] = api.clientInfo(client)
7166
})
7267
return res
7368
}
@@ -80,48 +75,40 @@ func (api *PrivateLightServerAPI) ClientInfo(ids []enode.ID) map[enode.ID]map[st
8075
// assigned to it.
8176
func (api *PrivateLightServerAPI) PriorityClientInfo(start, stop enode.ID, maxCount int) map[enode.ID]map[string]interface{} {
8277
res := make(map[enode.ID]map[string]interface{})
83-
ids := api.server.clientPool.ndb.getPosBalanceIDs(start, stop, maxCount+1)
78+
ids := api.server.clientPool.bt.GetPosBalanceIDs(start, stop, maxCount+1)
8479
if len(ids) > maxCount {
8580
res[ids[maxCount]] = make(map[string]interface{})
8681
ids = ids[:maxCount]
8782
}
8883
if len(ids) != 0 {
89-
api.server.clientPool.forClients(ids, func(client *clientInfo, id enode.ID) error {
90-
res[id] = api.clientInfo(client, id)
91-
return nil
84+
api.server.clientPool.forClients(ids, func(client *clientInfo) {
85+
res[client.node.ID()] = api.clientInfo(client)
9286
})
9387
}
9488
return res
9589
}
9690

9791
// clientInfo creates a client info data structure
98-
func (api *PrivateLightServerAPI) clientInfo(c *clientInfo, id enode.ID) map[string]interface{} {
92+
func (api *PrivateLightServerAPI) clientInfo(c *clientInfo) map[string]interface{} {
9993
info := make(map[string]interface{})
100-
if c != nil {
101-
now := mclock.Now()
102-
info["isConnected"] = true
103-
info["connectionTime"] = float64(now-c.connectedAt) / float64(time.Second)
104-
info["capacity"] = c.capacity
105-
pb, nb := c.balanceTracker.getBalance(now)
106-
info["pricing/balance"], info["pricing/negBalance"] = pb, nb
107-
info["pricing/balanceMeta"] = c.balanceMetaInfo
108-
info["priority"] = pb != 0
109-
} else {
110-
info["isConnected"] = false
111-
pb := api.server.clientPool.ndb.getOrNewPB(id)
112-
info["pricing/balance"], info["pricing/balanceMeta"] = pb.value, pb.meta
113-
info["priority"] = pb.value != 0
94+
pb, nb := c.balance.GetBalance()
95+
info["isConnected"] = c.connected
96+
info["pricing/balance"] = pb
97+
info["priority"] = pb != 0
98+
// cb := api.server.clientPool.ndb.getCurrencyBalance(id)
99+
// info["pricing/currency"] = cb.amount
100+
if c.connected {
101+
info["connectionTime"] = float64(mclock.Now()-c.connectedAt) / float64(time.Second)
102+
info["capacity"], _ = api.server.clientPool.ns.GetField(c.node, priorityPoolSetup.CapacityField).(uint64)
103+
info["pricing/negBalance"] = nb
114104
}
115105
return info
116106
}
117107

118108
// setParams either sets the given parameters for a single connected client (if specified)
119109
// or the default parameters applicable to clients connected in the future
120-
func (api *PrivateLightServerAPI) setParams(params map[string]interface{}, client *clientInfo, posFactors, negFactors *priceFactors) (updateFactors bool, err error) {
110+
func (api *PrivateLightServerAPI) setParams(params map[string]interface{}, client *clientInfo, posFactors, negFactors *lps.PriceFactors) (updateFactors bool, err error) {
121111
defParams := client == nil
122-
if !defParams {
123-
posFactors, negFactors = &client.posFactors, &client.negFactors
124-
}
125112
for name, value := range params {
126113
errValue := func() error {
127114
return fmt.Errorf("invalid value for parameter '%s'", name)
@@ -137,20 +124,20 @@ func (api *PrivateLightServerAPI) setParams(params map[string]interface{}, clien
137124

138125
switch {
139126
case name == "pricing/timeFactor":
140-
setFactor(&posFactors.timeFactor)
127+
setFactor(&posFactors.TimeFactor)
141128
case name == "pricing/capacityFactor":
142-
setFactor(&posFactors.capacityFactor)
129+
setFactor(&posFactors.CapacityFactor)
143130
case name == "pricing/requestCostFactor":
144-
setFactor(&posFactors.requestFactor)
131+
setFactor(&posFactors.RequestFactor)
145132
case name == "pricing/negative/timeFactor":
146-
setFactor(&negFactors.timeFactor)
133+
setFactor(&negFactors.TimeFactor)
147134
case name == "pricing/negative/capacityFactor":
148-
setFactor(&negFactors.capacityFactor)
135+
setFactor(&negFactors.CapacityFactor)
149136
case name == "pricing/negative/requestCostFactor":
150-
setFactor(&negFactors.requestFactor)
137+
setFactor(&negFactors.RequestFactor)
151138
case !defParams && name == "capacity":
152139
if capacity, ok := value.(float64); ok && uint64(capacity) >= api.server.minCapacity {
153-
err = api.server.clientPool.setCapacity(client, uint64(capacity))
140+
_, err = api.server.clientPool.setCapacity(client.node, client.address, uint64(capacity), 0, true)
154141
// Don't have to call factor update explicitly. It's already done
155142
// in setCapacity function.
156143
} else {
@@ -170,27 +157,25 @@ func (api *PrivateLightServerAPI) setParams(params map[string]interface{}, clien
170157
return
171158
}
172159

173-
// AddBalance updates the balance of a client (either overwrites it or adds to it).
174-
// It also updates the balance meta info string.
175-
func (api *PrivateLightServerAPI) AddBalance(id enode.ID, value int64, meta string) ([2]uint64, error) {
176-
oldBalance, newBalance, err := api.server.clientPool.addBalance(id, value, meta)
177-
return [2]uint64{oldBalance, newBalance}, err
178-
}
179-
180160
// SetClientParams sets client parameters for all clients listed in the ids list
181161
// or all connected clients if the list is empty
182162
func (api *PrivateLightServerAPI) SetClientParams(ids []enode.ID, params map[string]interface{}) error {
183-
return api.server.clientPool.forClients(ids, func(client *clientInfo, id enode.ID) error {
184-
if client != nil {
185-
update, err := api.setParams(params, client, nil, nil)
163+
var err error
164+
api.server.clientPool.forClients(ids, func(client *clientInfo) {
165+
if client.connected {
166+
posFactors, negFactors := client.balance.GetPriceFactors()
167+
update, e := api.setParams(params, client, &posFactors, &negFactors)
186168
if update {
187-
client.updatePriceFactors()
169+
client.balance.SetPriceFactors(posFactors, negFactors)
170+
}
171+
if e != nil {
172+
err = e
188173
}
189-
return err
190174
} else {
191-
return fmt.Errorf("client %064x is not connected", id[:])
175+
err = fmt.Errorf("client %064x is not connected", client.node.ID())
192176
}
193177
})
178+
return err
194179
}
195180

196181
// SetDefaultParams sets the default parameters applicable to clients connected in the future
@@ -214,6 +199,15 @@ func (api *PrivateLightServerAPI) SetConnectedBias(bias time.Duration) error {
214199
return nil
215200
}
216201

202+
// AddBalance adds the given amount to the balance of a client if possible and returns
203+
// the balance before and after the operation
204+
func (api *PrivateLightServerAPI) AddBalance(id enode.ID, amount int64) (balance [2]uint64, err error) {
205+
api.server.clientPool.forClients([]enode.ID{id}, func(c *clientInfo) {
206+
balance[0], balance[1], err = c.balance.AddBalance(amount)
207+
})
208+
return
209+
}
210+
217211
// Benchmark runs a request performance benchmark with a given set of measurement setups
218212
// in multiple passes specified by passCount. The measurement time for each setup in each
219213
// pass is specified in milliseconds by length.
@@ -304,13 +298,15 @@ func NewPrivateDebugAPI(server *LesServer) *PrivateDebugAPI {
304298

305299
// FreezeClient forces a temporary client freeze which normally happens when the server is overloaded
306300
func (api *PrivateDebugAPI) FreezeClient(id enode.ID) error {
307-
return api.server.clientPool.forClients([]enode.ID{id}, func(c *clientInfo, id enode.ID) error {
308-
if c == nil {
309-
return fmt.Errorf("client %064x is not connected", id[:])
301+
var err error
302+
api.server.clientPool.forClients([]enode.ID{id}, func(c *clientInfo) {
303+
if c.connected {
304+
c.peer.freeze()
305+
} else {
306+
err = fmt.Errorf("client %064x is not connected", id[:])
310307
}
311-
c.peer.freezeClient()
312-
return nil
313308
})
309+
return err
314310
}
315311

316312
// PrivateLightAPI provides an API to access the LES light server or light client.

‎les/api_test.go‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
107107
t.Fatalf("Failed to obtain rpc client: %v", err)
108108
}
109109
headNum, headHash := getHead(ctx, t, serverRpcClient)
110-
minCap, freeCap, totalCap := getCapacityInfo(ctx, t, serverRpcClient)
110+
minCap, totalCap := getCapacityInfo(ctx, t, serverRpcClient)
111111
testCap := totalCap * 3 / 4
112112
t.Logf("Server testCap: %d minCap: %d head number: %d head hash: %064x\n", testCap, minCap, headNum, headHash)
113113
reqMinCap := uint64(float64(testCap) * minRelCap / (minRelCap + float64(len(clients)-1)))
@@ -202,7 +202,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
202202

203203
weights := make([]float64, len(clients))
204204
for c := 0; c < 5; c++ {
205-
setCapacity(ctx, t, serverRpcClient, clients[freeIdx].ID(), freeCap)
205+
setCapacity(ctx, t, serverRpcClient, clients[freeIdx].ID(), minCap)
206206
freeIdx = rand.Intn(len(clients))
207207
var sum float64
208208
for i := range clients {
@@ -214,7 +214,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
214214
sum += weights[i]
215215
}
216216
for i, client := range clients {
217-
weights[i] *= float64(testCap-freeCap-100) / sum
217+
weights[i] *= float64(testCap-minCap-100) / sum
218218
capacity := uint64(weights[i])
219219
if i != freeIdx && capacity < getCapacity(ctx, t, serverRpcClient, client.ID()) {
220220
setCapacity(ctx, t, serverRpcClient, client.ID(), capacity)
@@ -227,7 +227,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
227227
setCapacity(ctx, t, serverRpcClient, client.ID(), capacity)
228228
}
229229
}
230-
weights[freeIdx] = float64(freeCap)
230+
weights[freeIdx] = float64(minCap)
231231
for i := range clients {
232232
weights[i] /= float64(testCap)
233233
}
@@ -247,7 +247,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
247247
default:
248248
}
249249

250-
_, _, totalCap = getCapacityInfo(ctx, t, serverRpcClient)
250+
_, totalCap = getCapacityInfo(ctx, t, serverRpcClient)
251251
if totalCap < testCap {
252252
t.Log("Total capacity underrun")
253253
close(stop)
@@ -370,7 +370,7 @@ func getCapacity(ctx context.Context, t *testing.T, server *rpc.Client, clientID
370370
return uint64(vv)
371371
}
372372

373-
func getCapacityInfo(ctx context.Context, t *testing.T, server *rpc.Client) (minCap, freeCap, totalCap uint64) {
373+
func getCapacityInfo(ctx context.Context, t *testing.T, server *rpc.Client) (minCap, totalCap uint64) {
374374
var res map[string]interface{}
375375
if err := server.CallContext(ctx, &res, "les_serverInfo"); err != nil {
376376
t.Fatalf("Failed to query server info: %v", err)
@@ -387,7 +387,6 @@ func getCapacityInfo(ctx context.Context, t *testing.T, server *rpc.Client) (min
387387
return uint64(vv)
388388
}
389389
minCap = decode("minimumCapacity")
390-
freeCap = decode("freeClientCapacity")
391390
totalCap = decode("totalCapacity")
392391
return
393392
}

0 commit comments

Comments
 (0)