Skip to content

Commit b2ddb1f

Browse files
zsfelfoldifjl
authored andcommitted
les: implement client connection logic (#16899)
This PR implements les.freeClientPool. It also adds a simulated clock in common/mclock, which enables time-sensitive tests to run quickly and still produce accurate results, and package common/prque which is a generalised variant of prque that enables removing elements other than the top one from the queue. les.freeClientPool implements a client database that limits the connection time of each client and manages accepting/rejecting incoming connections and even kicking out some connected clients. The pool calculates recent usage time for each known client (a value that increases linearly when the client is connected and decreases exponentially when not connected). Clients with lower recent usage are preferred, unknown nodes have the highest priority. Already connected nodes receive a small bias in their favor in order to avoid accepting and instantly kicking out clients. Note: the pool can use any string for client identification. Using signature keys for that purpose would not make sense when being known has a negative value for the client. Currently the LES protocol manager uses IP addresses (without port address) to identify clients.
1 parent a1783d1 commit b2ddb1f

7 files changed

Lines changed: 761 additions & 1 deletion

File tree

‎common/mclock/mclock.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,34 @@ type AbsTime time.Duration
3030
func Now() AbsTime {
3131
return AbsTime(monotime.Now())
3232
}
33+
34+
// Add returns t + d.
35+
func (t AbsTime) Add(d time.Duration) AbsTime {
36+
return t + AbsTime(d)
37+
}
38+
39+
// Clock interface makes it possible to replace the monotonic system clock with
40+
// a simulated clock.
41+
type Clock interface {
42+
Now() AbsTime
43+
Sleep(time.Duration)
44+
After(time.Duration) <-chan time.Time
45+
}
46+
47+
// System implements Clock using the system clock.
48+
type System struct{}
49+
50+
// Now implements Clock.
51+
func (System) Now() AbsTime {
52+
return AbsTime(monotime.Now())
53+
}
54+
55+
// Sleep implements Clock.
56+
func (System) Sleep(d time.Duration) {
57+
time.Sleep(d)
58+
}
59+
60+
// After implements Clock.
61+
func (System) After(d time.Duration) <-chan time.Time {
62+
return time.After(d)
63+
}

‎common/mclock/simclock.go‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// Copyright 2018 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+
17+
package mclock
18+
19+
import (
20+
"sync"
21+
"time"
22+
)
23+
24+
// Simulated implements a virtual Clock for reproducible time-sensitive tests. It
25+
// simulates a scheduler on a virtual timescale where actual processing takes zero time.
26+
//
27+
// The virtual clock doesn't advance on its own, call Run to advance it and execute timers.
28+
// Since there is no way to influence the Go scheduler, testing timeout behaviour involving
29+
// goroutines needs special care. A good way to test such timeouts is as follows: First
30+
// perform the action that is supposed to time out. Ensure that the timer you want to test
31+
// is created. Then run the clock until after the timeout. Finally observe the effect of
32+
// the timeout using a channel or semaphore.
33+
type Simulated struct {
34+
now AbsTime
35+
scheduled []event
36+
mu sync.RWMutex
37+
cond *sync.Cond
38+
}
39+
40+
type event struct {
41+
do func()
42+
at AbsTime
43+
}
44+
45+
// Run moves the clock by the given duration, executing all timers before that duration.
46+
func (s *Simulated) Run(d time.Duration) {
47+
s.mu.Lock()
48+
defer s.mu.Unlock()
49+
s.init()
50+
51+
end := s.now + AbsTime(d)
52+
for len(s.scheduled) > 0 {
53+
ev := s.scheduled[0]
54+
if ev.at > end {
55+
break
56+
}
57+
s.now = ev.at
58+
ev.do()
59+
s.scheduled = s.scheduled[1:]
60+
}
61+
s.now = end
62+
}
63+
64+
func (s *Simulated) ActiveTimers() int {
65+
s.mu.RLock()
66+
defer s.mu.RUnlock()
67+
68+
return len(s.scheduled)
69+
}
70+
71+
func (s *Simulated) WaitForTimers(n int) {
72+
s.mu.Lock()
73+
defer s.mu.Unlock()
74+
s.init()
75+
76+
for len(s.scheduled) < n {
77+
s.cond.Wait()
78+
}
79+
}
80+
81+
// Now implements Clock.
82+
func (s *Simulated) Now() AbsTime {
83+
s.mu.RLock()
84+
defer s.mu.RUnlock()
85+
86+
return s.now
87+
}
88+
89+
// Sleep implements Clock.
90+
func (s *Simulated) Sleep(d time.Duration) {
91+
<-s.After(d)
92+
}
93+
94+
// After implements Clock.
95+
func (s *Simulated) After(d time.Duration) <-chan time.Time {
96+
after := make(chan time.Time, 1)
97+
s.insert(d, func() {
98+
after <- (time.Time{}).Add(time.Duration(s.now))
99+
})
100+
return after
101+
}
102+
103+
func (s *Simulated) insert(d time.Duration, do func()) {
104+
s.mu.Lock()
105+
defer s.mu.Unlock()
106+
s.init()
107+
108+
at := s.now + AbsTime(d)
109+
l, h := 0, len(s.scheduled)
110+
ll := h
111+
for l != h {
112+
m := (l + h) / 2
113+
if at < s.scheduled[m].at {
114+
h = m
115+
} else {
116+
l = m + 1
117+
}
118+
}
119+
s.scheduled = append(s.scheduled, event{})
120+
copy(s.scheduled[l+1:], s.scheduled[l:ll])
121+
s.scheduled[l] = event{do: do, at: at}
122+
s.cond.Broadcast()
123+
}
124+
125+
func (s *Simulated) init() {
126+
if s.cond == nil {
127+
s.cond = sync.NewCond(&s.mu)
128+
}
129+
}

‎common/prque/prque.go‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// This is a duplicated and slightly modified version of "gopkg.in/karalabe/cookiejar.v2/collections/prque".
2+
3+
package prque
4+
5+
import (
6+
"container/heap"
7+
)
8+
9+
// Priority queue data structure.
10+
type Prque struct {
11+
cont *sstack
12+
}
13+
14+
// Creates a new priority queue.
15+
func New(setIndex setIndexCallback) *Prque {
16+
return &Prque{newSstack(setIndex)}
17+
}
18+
19+
// Pushes a value with a given priority into the queue, expanding if necessary.
20+
func (p *Prque) Push(data interface{}, priority int64) {
21+
heap.Push(p.cont, &item{data, priority})
22+
}
23+
24+
// Pops the value with the greates priority off the stack and returns it.
25+
// Currently no shrinking is done.
26+
func (p *Prque) Pop() (interface{}, int64) {
27+
item := heap.Pop(p.cont).(*item)
28+
return item.value, item.priority
29+
}
30+
31+
// Pops only the item from the queue, dropping the associated priority value.
32+
func (p *Prque) PopItem() interface{} {
33+
return heap.Pop(p.cont).(*item).value
34+
}
35+
36+
// Remove removes the element with the given index.
37+
func (p *Prque) Remove(i int) interface{} {
38+
if i < 0 {
39+
return nil
40+
}
41+
return heap.Remove(p.cont, i)
42+
}
43+
44+
// Checks whether the priority queue is empty.
45+
func (p *Prque) Empty() bool {
46+
return p.cont.Len() == 0
47+
}
48+
49+
// Returns the number of element in the priority queue.
50+
func (p *Prque) Size() int {
51+
return p.cont.Len()
52+
}
53+
54+
// Clears the contents of the priority queue.
55+
func (p *Prque) Reset() {
56+
*p = *New(p.cont.setIndex)
57+
}

‎common/prque/sstack.go‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// This is a duplicated and slightly modified version of "gopkg.in/karalabe/cookiejar.v2/collections/prque".
2+
3+
package prque
4+
5+
// The size of a block of data
6+
const blockSize = 4096
7+
8+
// A prioritized item in the sorted stack.
9+
//
10+
// Note: priorities can "wrap around" the int64 range, a comes before b if (a.priority - b.priority) > 0.
11+
// The difference between the lowest and highest priorities in the queue at any point should be less than 2^63.
12+
type item struct {
13+
value interface{}
14+
priority int64
15+
}
16+
17+
// setIndexCallback is called when the element is moved to a new index.
18+
// Providing setIndexCallback is optional, it is needed only if the application needs
19+
// to delete elements other than the top one.
20+
type setIndexCallback func(a interface{}, i int)
21+
22+
// Internal sortable stack data structure. Implements the Push and Pop ops for
23+
// the stack (heap) functionality and the Len, Less and Swap methods for the
24+
// sortability requirements of the heaps.
25+
type sstack struct {
26+
setIndex setIndexCallback
27+
size int
28+
capacity int
29+
offset int
30+
31+
blocks [][]*item
32+
active []*item
33+
}
34+
35+
// Creates a new, empty stack.
36+
func newSstack(setIndex setIndexCallback) *sstack {
37+
result := new(sstack)
38+
result.setIndex = setIndex
39+
result.active = make([]*item, blockSize)
40+
result.blocks = [][]*item{result.active}
41+
result.capacity = blockSize
42+
return result
43+
}
44+
45+
// Pushes a value onto the stack, expanding it if necessary. Required by
46+
// heap.Interface.
47+
func (s *sstack) Push(data interface{}) {
48+
if s.size == s.capacity {
49+
s.active = make([]*item, blockSize)
50+
s.blocks = append(s.blocks, s.active)
51+
s.capacity += blockSize
52+
s.offset = 0
53+
} else if s.offset == blockSize {
54+
s.active = s.blocks[s.size/blockSize]
55+
s.offset = 0
56+
}
57+
if s.setIndex != nil {
58+
s.setIndex(data.(*item).value, s.size)
59+
}
60+
s.active[s.offset] = data.(*item)
61+
s.offset++
62+
s.size++
63+
}
64+
65+
// Pops a value off the stack and returns it. Currently no shrinking is done.
66+
// Required by heap.Interface.
67+
func (s *sstack) Pop() (res interface{}) {
68+
s.size--
69+
s.offset--
70+
if s.offset < 0 {
71+
s.offset = blockSize - 1
72+
s.active = s.blocks[s.size/blockSize]
73+
}
74+
res, s.active[s.offset] = s.active[s.offset], nil
75+
if s.setIndex != nil {
76+
s.setIndex(res.(*item).value, -1)
77+
}
78+
return
79+
}
80+
81+
// Returns the length of the stack. Required by sort.Interface.
82+
func (s *sstack) Len() int {
83+
return s.size
84+
}
85+
86+
// Compares the priority of two elements of the stack (higher is first).
87+
// Required by sort.Interface.
88+
func (s *sstack) Less(i, j int) bool {
89+
return (s.blocks[i/blockSize][i%blockSize].priority - s.blocks[j/blockSize][j%blockSize].priority) > 0
90+
}
91+
92+
// Swaps two elements in the stack. Required by sort.Interface.
93+
func (s *sstack) Swap(i, j int) {
94+
ib, io, jb, jo := i/blockSize, i%blockSize, j/blockSize, j%blockSize
95+
a, b := s.blocks[jb][jo], s.blocks[ib][io]
96+
if s.setIndex != nil {
97+
s.setIndex(a.value, i)
98+
s.setIndex(b.value, j)
99+
}
100+
s.blocks[ib][io], s.blocks[jb][jo] = a, b
101+
}
102+
103+
// Resets the stack, effectively clearing its contents.
104+
func (s *sstack) Reset() {
105+
*s = *newSstack(s.setIndex)
106+
}

0 commit comments

Comments
 (0)