Skip to content

Commit dd6095f

Browse files
authored
introduce new disk LRU in LevelDB (keybase#11029)
1 parent 646dfa4 commit dd6095f

3 files changed

Lines changed: 490 additions & 3 deletions

File tree

‎go/libkb/db.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,9 @@ const (
167167
DBSig = 0x0f
168168
DBTeamChain = 0x10
169169
DBUserPlusAllKeysV1 = 0x19
170-
// NOTE: This file needs to stay consistent with config/id.iced on the
171-
// website, and that one has IDs on the lower end of the range that aren't
172-
// represented here.
170+
171+
DBDiskLRUEntries = 0xda
172+
DBDiskLRUIndex = 0xdb
173173
DBImplicitTeamConflictInfo = 0xdc
174174
DBUidToFullName = 0xdd
175175
DBUidToUsername = 0xde

‎go/lru/disk_lru.go‎

Lines changed: 357 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,357 @@
1+
package lru
2+
3+
import (
4+
"container/list"
5+
"errors"
6+
"fmt"
7+
"sync"
8+
"time"
9+
10+
"github.com/keybase/client/go/libkb"
11+
context "golang.org/x/net/context"
12+
)
13+
14+
type DiskLRUEntry struct {
15+
Key string
16+
Value interface{}
17+
Ctime time.Time
18+
LastAccessed time.Time
19+
}
20+
21+
type diskLRUIndexMarshaled struct {
22+
Version int
23+
EntryKeys []string
24+
}
25+
26+
type diskLRUIndex struct {
27+
sync.Mutex
28+
Version int
29+
EntryKeys *list.List
30+
entryKeyMap map[string]*list.Element
31+
dirty bool
32+
}
33+
34+
func newDiskLRUIndex(version int) *diskLRUIndex {
35+
return &diskLRUIndex{
36+
EntryKeys: list.New(),
37+
Version: version,
38+
entryKeyMap: make(map[string]*list.Element),
39+
}
40+
}
41+
42+
func (d *diskLRUIndex) exists(key string) *list.Element {
43+
return d.entryKeyMap[key]
44+
}
45+
46+
func (d *diskLRUIndex) Exists(key string) bool {
47+
d.Lock()
48+
defer d.Unlock()
49+
return (d.exists(key) != nil)
50+
}
51+
52+
func (d *diskLRUIndex) remove(key string) {
53+
if el, ok := d.entryKeyMap[key]; ok {
54+
d.EntryKeys.Remove(el)
55+
delete(d.entryKeyMap, key)
56+
}
57+
}
58+
59+
func (d *diskLRUIndex) Remove(key string) {
60+
d.Lock()
61+
defer d.Unlock()
62+
d.dirty = true
63+
d.remove(key)
64+
}
65+
66+
func (d *diskLRUIndex) put(key string) {
67+
d.entryKeyMap[key] = d.EntryKeys.PushFront(key)
68+
}
69+
70+
func (d *diskLRUIndex) Put(key string) {
71+
d.Lock()
72+
defer d.Unlock()
73+
d.dirty = true
74+
if d.exists(key) != nil {
75+
d.remove(key)
76+
}
77+
d.put(key)
78+
}
79+
80+
func (d *diskLRUIndex) IsDirty() bool {
81+
d.Lock()
82+
defer d.Unlock()
83+
return d.dirty
84+
}
85+
86+
func (d *diskLRUIndex) ClearDirty() {
87+
d.Lock()
88+
defer d.Unlock()
89+
d.dirty = false
90+
}
91+
92+
func (d *diskLRUIndex) Marshal() diskLRUIndexMarshaled {
93+
var m diskLRUIndexMarshaled
94+
m.Version = d.Version
95+
for e := d.EntryKeys.Front(); e != nil; e = e.Next() {
96+
m.EntryKeys = append(m.EntryKeys, e.Value.(string))
97+
}
98+
return m
99+
}
100+
101+
func (d *diskLRUIndex) Unmarshal(m diskLRUIndexMarshaled) {
102+
d.EntryKeys = list.New()
103+
d.Version = m.Version
104+
d.entryKeyMap = make(map[string]*list.Element)
105+
for _, k := range m.EntryKeys {
106+
d.entryKeyMap[k] = d.EntryKeys.PushBack(k)
107+
}
108+
}
109+
110+
func (d *diskLRUIndex) Size() int {
111+
d.Lock()
112+
d.Unlock()
113+
return d.EntryKeys.Len()
114+
}
115+
116+
func (d *diskLRUIndex) OldestKey() (string, error) {
117+
d.Lock()
118+
defer d.Unlock()
119+
if d.EntryKeys.Len() == 0 {
120+
return "", errors.New("index is empty")
121+
}
122+
return d.EntryKeys.Back().Value.(string), nil
123+
}
124+
125+
// DiskLRU maintains a cache of files on the disk in a LRU manner.
126+
type DiskLRU struct {
127+
sync.Mutex
128+
129+
index *diskLRUIndex
130+
name string
131+
version int
132+
maxSize int
133+
134+
lastFlush time.Time
135+
flushDuration time.Duration
136+
137+
// testing
138+
flushCh chan struct{}
139+
}
140+
141+
func NewDiskLRU(name string, version int, maxSize int) *DiskLRU {
142+
return &DiskLRU{
143+
name: name,
144+
version: version,
145+
maxSize: maxSize,
146+
flushDuration: time.Minute,
147+
}
148+
}
149+
150+
func (d *DiskLRU) debug(ctx context.Context, lctx libkb.LRUContext, msg string, args ...interface{}) {
151+
lctx.GetLog().CDebugf(ctx, fmt.Sprintf("DiskLRU: %s(%d): ", d.name, d.version)+msg, args...)
152+
}
153+
154+
func (d *DiskLRU) indexKey() libkb.DbKey {
155+
return libkb.DbKey{
156+
Typ: libkb.DBDiskLRUIndex,
157+
Key: fmt.Sprintf("%s:%d", d.name, d.version),
158+
}
159+
}
160+
161+
func (d *DiskLRU) entryKey(key string) libkb.DbKey {
162+
return libkb.DbKey{
163+
Typ: libkb.DBDiskLRUEntries,
164+
Key: fmt.Sprintf("%s:%d:%s", d.name, d.version, key),
165+
}
166+
}
167+
168+
func (d *DiskLRU) readIndex(ctx context.Context, lctx libkb.LRUContext) (res *diskLRUIndex, err error) {
169+
// Check memory and stash if we read with no error
170+
if d.index != nil {
171+
return d.index, nil
172+
}
173+
defer func() {
174+
if err == nil && res != nil {
175+
d.index = res
176+
}
177+
}()
178+
179+
// Grab from the disk if we miss on memory
180+
var marshalIndex diskLRUIndexMarshaled
181+
res = new(diskLRUIndex)
182+
found, err := lctx.GetKVStore().GetInto(&marshalIndex, d.indexKey())
183+
if err != nil {
184+
return nil, err
185+
}
186+
if !found {
187+
return newDiskLRUIndex(d.version), nil
188+
}
189+
res.Unmarshal(marshalIndex)
190+
return res, nil
191+
}
192+
193+
func (d *DiskLRU) writeIndex(ctx context.Context, lctx libkb.LRUContext, index *diskLRUIndex,
194+
forceFlush bool) error {
195+
if forceFlush || lctx.GetClock().Now().Sub(d.lastFlush) > d.flushDuration {
196+
marshalIndex := index.Marshal()
197+
if err := lctx.GetKVStore().PutObj(d.indexKey(), nil, marshalIndex); err != nil {
198+
return err
199+
}
200+
d.lastFlush = lctx.GetClock().Now()
201+
index.ClearDirty()
202+
if d.flushCh != nil {
203+
d.flushCh <- struct{}{}
204+
}
205+
}
206+
return nil
207+
}
208+
209+
func (d *DiskLRU) readEntry(ctx context.Context, lctx libkb.LRUContext, key string) (found bool, res DiskLRUEntry, err error) {
210+
found, err = lctx.GetKVStore().GetInto(&res, d.entryKey(key))
211+
if err != nil {
212+
return false, res, err
213+
}
214+
if !found {
215+
return false, res, nil
216+
}
217+
return true, res, nil
218+
}
219+
220+
func (d *DiskLRU) accessEntry(ctx context.Context, lctx libkb.LRUContext, index *diskLRUIndex,
221+
entry *DiskLRUEntry) error {
222+
// Promote the key in the index
223+
index.Put(entry.Key)
224+
// Write out the entry with new accessed time
225+
entry.LastAccessed = lctx.GetClock().Now()
226+
return lctx.GetKVStore().PutObj(d.entryKey(entry.Key), nil, entry)
227+
}
228+
229+
func (d *DiskLRU) Get(ctx context.Context, lctx libkb.LRUContext, key string) (found bool, res DiskLRUEntry, err error) {
230+
d.Lock()
231+
defer d.Unlock()
232+
233+
var index *diskLRUIndex
234+
defer func() {
235+
// Commit the index
236+
if err == nil && index != nil && index.IsDirty() {
237+
d.writeIndex(ctx, lctx, index, false)
238+
}
239+
}()
240+
241+
// Grab entry index
242+
index, err = d.readIndex(ctx, lctx)
243+
if err != nil {
244+
return found, res, err
245+
}
246+
// Check for a straight up miss
247+
if !index.Exists(key) {
248+
return false, res, nil
249+
}
250+
// Read entry
251+
found, res, err = d.readEntry(ctx, lctx, key)
252+
if err != nil {
253+
return found, res, err
254+
}
255+
if !found {
256+
// remove from index
257+
index.Remove(key)
258+
return false, res, nil
259+
}
260+
// update last accessed time for the entry
261+
if err = d.accessEntry(ctx, lctx, index, &res); err != nil {
262+
return found, res, err
263+
}
264+
265+
return true, res, nil
266+
}
267+
268+
func (d *DiskLRU) removeEntry(ctx context.Context, lctx libkb.LRUContext, index *diskLRUIndex, key string) error {
269+
index.Remove(key)
270+
return lctx.GetKVStore().Delete(d.entryKey(key))
271+
}
272+
273+
func (d *DiskLRU) addEntry(ctx context.Context, lctx libkb.LRUContext, index *diskLRUIndex, key string,
274+
value interface{}) (evicted *DiskLRUEntry, err error) {
275+
276+
// Add the new item
277+
index.Put(key)
278+
item := DiskLRUEntry{
279+
Key: key,
280+
Value: value,
281+
Ctime: lctx.GetClock().Now(),
282+
LastAccessed: lctx.GetClock().Now(),
283+
}
284+
if err = lctx.GetKVStore().PutObj(d.entryKey(key), nil, item); err != nil {
285+
return nil, err
286+
}
287+
288+
if index.Size() > d.maxSize {
289+
// Evict the oldest item
290+
var found bool
291+
var lastItem DiskLRUEntry
292+
lastKey, err := index.OldestKey()
293+
if err == nil {
294+
found, lastItem, err = d.readEntry(ctx, lctx, lastKey)
295+
if err != nil {
296+
return nil, err
297+
}
298+
if found {
299+
evicted = &lastItem
300+
d.debug(ctx, lctx, "addEntry: evicting item: key: %s", lastKey)
301+
}
302+
if err = d.removeEntry(ctx, lctx, index, lastKey); err != nil {
303+
return nil, err
304+
}
305+
} else {
306+
d.debug(ctx, lctx, "addEntry: failed to find oldest key, check cache config")
307+
}
308+
}
309+
310+
return evicted, nil
311+
}
312+
313+
func (d *DiskLRU) Put(ctx context.Context, lctx libkb.LRUContext, key string, value interface{}) (evicted *DiskLRUEntry, err error) {
314+
d.Lock()
315+
defer d.Unlock()
316+
317+
var index *diskLRUIndex
318+
defer func() {
319+
// Commit the index
320+
if err == nil && index != nil && index.IsDirty() {
321+
d.writeIndex(ctx, lctx, index, false)
322+
}
323+
}()
324+
325+
// Grab entry index
326+
index, err = d.readIndex(ctx, lctx)
327+
if err != nil {
328+
return nil, err
329+
}
330+
// Remove existing entry from the index (we don't need to remove entry off the disk, since we will
331+
// overwrite it with new stuff)
332+
if index.Exists(key) {
333+
index.Remove(key)
334+
}
335+
// Add the item
336+
return d.addEntry(ctx, lctx, index, key, value)
337+
}
338+
339+
func (d *DiskLRU) ClearMemory(ctx context.Context, lctx libkb.LRUContext) {
340+
d.Lock()
341+
defer d.Unlock()
342+
d.flush(ctx, lctx)
343+
d.index = nil
344+
}
345+
346+
func (d *DiskLRU) flush(ctx context.Context, lctx libkb.LRUContext) error {
347+
if d.index != nil {
348+
return d.writeIndex(ctx, lctx, d.index, true)
349+
}
350+
return nil
351+
}
352+
353+
func (d *DiskLRU) Flush(ctx context.Context, lctx libkb.LRUContext) error {
354+
d.Lock()
355+
defer d.Unlock()
356+
return d.flush(ctx, lctx)
357+
}

0 commit comments

Comments
 (0)