forked from lni/dragonboat
/
lrusession.go
195 lines (181 loc) · 4.75 KB
/
lrusession.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2017-2019 Lei Ni (nilei81@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rsm
import (
"bytes"
"crypto/md5"
"encoding/binary"
"io"
"sync"
"github.com/lni/dragonboat/internal/utils/cache"
)
// lrusession is a session manager that keeps up to size number of client
// sessions. LRU is the policy for evicting old ones.
type lrusession struct {
sync.Mutex
size uint64
sessions *cache.OrderedCache
searchKey RaftClientID
}
// Newlrusession returns a new lrusession instance that can hold up to size
// client sessions.
func newLRUSession(size uint64) *lrusession {
if size == 0 {
panic("lrusession size must be > 0")
}
rec := &lrusession{
size: size,
sessions: cache.NewOrderedCache(cache.Config{Policy: cache.CacheLRU}),
}
rec.sessions.Config.ShouldEvict = func(n int, k, v interface{}) bool {
if uint64(n) > rec.size {
clientID := k.(*RaftClientID)
plog.Warningf("session with client id %d evicted, overloaded", *clientID)
return true
}
return false
}
rec.sessions.Config.OnEvicted = func(k, v, e interface{}) {}
return rec
}
// GetSession returns the client session identified by the key.
func (rec *lrusession) getSession(key RaftClientID) (*Session, bool) {
rec.Lock()
defer rec.Unlock()
return rec.getSessionLocked(key)
}
// Save checkpoints the state of the lrusession and save the checkpointed
// state into the writer.
func (rec *lrusession) save(writer io.Writer) (uint64, error) {
rec.Lock()
defer rec.Unlock()
idList := make([]RaftClientID, 0)
rec.sessions.OrderedDo(func(k, v interface{}) {
key := k.(*RaftClientID)
idList = append(idList, *key)
})
sz := uint64(0)
totalbuf := make([]byte, 8)
binary.LittleEndian.PutUint64(totalbuf, rec.size)
_, err := writer.Write(totalbuf)
if err != nil {
return 0, err
}
sz += 8
binary.LittleEndian.PutUint64(totalbuf, uint64(len(idList)))
_, err = writer.Write(totalbuf)
if err != nil {
return 0, err
}
sz += 8
for _, key := range idList {
session, ok := rec.getSessionLocked(key)
if !ok || session == nil {
panic("bad state")
}
sessionSize, err := session.save(writer)
if err != nil {
return 0, err
}
sz += sessionSize
}
return sz, nil
}
// Load restores the state the of lrusession from the provided reader.
// reader contains lrusession state previously checkpointed.
func (rec *lrusession) load(reader io.Reader) error {
rec.Lock()
defer rec.Unlock()
sessionList := make([]*Session, 0)
sizebuf := make([]byte, 8)
n, err := io.ReadFull(reader, sizebuf)
if err != nil {
return err
}
if n != len(sizebuf) {
return io.ErrUnexpectedEOF
}
sz := binary.LittleEndian.Uint64(sizebuf)
n, err = io.ReadFull(reader, sizebuf)
if err != nil {
return err
}
if n != len(sizebuf) {
return io.ErrUnexpectedEOF
}
total := binary.LittleEndian.Uint64(sizebuf)
for i := uint64(0); i < total; i++ {
s, err := createSessionFromSnapshot(reader)
if err != nil {
return err
}
sessionList = append(sessionList, s)
}
newRec := newLRUSession(sz)
rec.sessions = newRec.sessions
rec.size = sz
for _, s := range sessionList {
rec.addSessionLocked(s.ClientID, *s)
}
return nil
}
func (rec *lrusession) makeEntry(key RaftClientID,
value Session) *cache.Entry {
alloc := struct {
key RaftClientID
value Session
entry cache.Entry
}{
key: key,
value: value,
}
alloc.entry.Key = &alloc.key
alloc.entry.Value = &alloc.value
return &alloc.entry
}
func (rec *lrusession) addSession(key RaftClientID, s Session) {
rec.Lock()
defer rec.Unlock()
rec.addSessionLocked(key, s)
}
func (rec *lrusession) addSessionLocked(key RaftClientID, s Session) {
entry := rec.makeEntry(key, s)
rec.sessions.AddEntry(entry)
}
func (rec *lrusession) getSessionLocked(key RaftClientID) (*Session, bool) {
rec.searchKey = key
v, ok := rec.sessions.Get(&rec.searchKey)
if ok {
return v.(*Session), ok
}
return nil, ok
}
func (rec *lrusession) delSession(key RaftClientID) {
rec.Lock()
defer rec.Unlock()
rec.sessions.Del(&key)
}
func (rec *lrusession) getHash() uint64 {
snapshot := &bytes.Buffer{}
if _, err := rec.save(snapshot); err != nil {
panic(err)
}
data := snapshot.Bytes()
hash := md5.New()
if _, err := hash.Write(data); err != nil {
panic(err)
}
md5sum := hash.Sum(nil)
return binary.LittleEndian.Uint64(md5sum[:8])
}