forked from etix/mirrorbits
/
cache.go
312 lines (286 loc) · 7.81 KB
/
cache.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright (c) 2014 Ludovic Fauvet
// Licensed under the MIT license
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"os"
"strconv"
"strings"
"sync"
"time"
"unsafe"
)
const (
FILE_UPDATE = "file_update"
MIRROR_UPDATE = "mirror_update"
MIRROR_FILE_UPDATE = "mirror_file_update"
)
// Cache implements a local caching mechanism of type LRU for content available in the
// redis database that is automatically invalidated if the object is updated in Redis.
type Cache struct {
r *redisobj
fiCache *LRUCache
fmCache *LRUCache
mCache *LRUCache
fimCache *LRUCache
extSubscribers map[string][]chan string
extSubscribersLock sync.RWMutex
}
type fileInfoValue struct {
value FileInfo
}
func (f *fileInfoValue) Size() int {
return int(unsafe.Sizeof(f.value))
}
type fileMirrorValue struct {
value []string
}
func (f *fileMirrorValue) Size() int {
return cap(f.value)
}
type mirrorValue struct {
value Mirror
}
func (f *mirrorValue) Size() int {
return int(unsafe.Sizeof(f.value))
}
// NewCache constructs a new instance of Cache
func NewCache(r *redisobj) *Cache {
cache := new(Cache)
cache.r = r
cache.fiCache = NewLRUCache(1024000)
cache.fmCache = NewLRUCache(2048000)
cache.mCache = NewLRUCache(1024000)
cache.fimCache = NewLRUCache(4096000)
cache.extSubscribers = make(map[string][]chan string)
go cache.updateEvents()
return cache
}
// SubscribeEvent allows subscription to a particular kind of events and send a
// notification to the given channel when an object is updated in the database.
func (c *Cache) SubscribeEvent(event string, channel chan string) {
c.extSubscribersLock.Lock()
defer c.extSubscribersLock.Unlock()
listeners := c.extSubscribers[event]
listeners = append(listeners, channel)
c.extSubscribers[event] = listeners
}
func (c *Cache) updateEvents() {
var disconnected bool = false
connect:
for {
rconn, err := redis.DialTimeout("tcp", GetConfig().RedisAddress, redisConnectionTimeout, 0, 200*time.Millisecond)
if err != nil {
disconnected = true
time.Sleep(50 * time.Millisecond)
continue
}
if _, err = rconn.Do("PING"); err != nil {
// Doing a PING after (re-connection) prevents cases where redis
// is currently loading the dataset and is still not ready.
// "LOADING Redis is loading the dataset in memory"
rconn.Close()
log.Info("Redis is loading the dataset in memory")
time.Sleep(500 * time.Millisecond)
continue
}
log.Info("Redis connected, subscribing pubsub.")
psc := redis.PubSubConn{Conn: rconn}
psc.Subscribe(FILE_UPDATE)
psc.Subscribe(MIRROR_UPDATE)
psc.Subscribe(MIRROR_FILE_UPDATE)
if disconnected == true {
// This is a way to keep the cache active while disconnected
// from redis but still clear the cache (possibly outdated)
// after a successful reconnection.
disconnected = false
c.Clear()
}
for {
switch v := psc.Receive().(type) {
case redis.Message:
//if os.Getenv("DEBUG") != "" {
// fmt.Printf("Redis message on channel %s: message: %s\n", v.Channel, v.Data)
//}
c.handleMessage(v.Channel, v.Data)
case redis.Subscription:
if os.Getenv("DEBUG") != "" {
log.Debug("Redis subscription event on channel %s: %s %d\n", v.Channel, v.Kind, v.Count)
}
case error:
log.Error("UpdateEvents error: %s", v)
psc.Close()
rconn.Close()
time.Sleep(50 * time.Millisecond)
disconnected = true
goto connect
}
}
}
}
func (c *Cache) handleMessage(channel string, data []byte) {
switch channel {
case FILE_UPDATE:
c.fiCache.Delete(string(data))
case MIRROR_UPDATE:
c.mCache.Delete(string(data))
case MIRROR_FILE_UPDATE:
s := strings.SplitN(string(data), " ", 2)
c.fmCache.Delete(s[1])
c.fimCache.Delete(fmt.Sprintf("%s|%s", s[0], s[1]))
}
// Notify external subscribers
c.extSubscribersLock.RLock()
defer c.extSubscribersLock.RUnlock()
listeners := c.extSubscribers[channel]
for _, listener := range listeners {
select {
case listener <- string(data):
default:
}
}
}
// Clear clears the local cache
func (c *Cache) Clear() {
c.fiCache.Clear()
c.fmCache.Clear()
c.mCache.Clear()
c.fimCache.Clear()
}
// GetFileInfo returns file informations for a given file either from the cache
// or directly from the database if the object is not yet stored in the cache.
func (c *Cache) GetFileInfo(path string) (f FileInfo, err error) {
v, ok := c.fiCache.Get(path)
if ok {
f = v.(*fileInfoValue).value
} else {
f, err = c.fetchFileInfo(path)
}
return
}
func (c *Cache) fetchFileInfo(path string) (f FileInfo, err error) {
rconn := c.r.pool.Get()
defer rconn.Close()
reply, err := redis.Strings(rconn.Do("HMGET", fmt.Sprintf("FILE_%s", path), "size", "modTime", "sha1"))
if err != nil {
// Put at least the path in the response
f.Path = path
return
}
f.Path = path
f.Size, _ = strconv.ParseInt(reply[0], 10, 64)
f.ModTime, _ = time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", reply[1])
f.Sha1 = reply[2]
c.fiCache.Set(path, &fileInfoValue{value: f})
return
}
// GetMirrors returns all the mirrors serving a given file either from the cache
// or directly from the database if the object is not yet stored in the cache.
func (c *Cache) GetMirrors(path string, clientInfo GeoIPRec) (mirrors []Mirror, err error) {
var mirrorsIDs []string
v, ok := c.fmCache.Get(path)
if ok {
mirrorsIDs = v.(*fileMirrorValue).value
} else {
mirrorsIDs, err = c.fetchFileMirrors(path)
if err != nil {
return
}
}
mirrors = make([]Mirror, 0, len(mirrorsIDs))
for _, id := range mirrorsIDs {
var mirror Mirror
var fileInfo FileInfo
v, ok := c.mCache.Get(id)
if ok {
mirror = v.(*mirrorValue).value
} else {
//TODO execute missing items in a MULTI query
mirror, err = c.fetchMirror(id)
if err != nil {
return
}
}
v, ok = c.fimCache.Get(fmt.Sprintf("%s|%s", id, path))
if ok {
fileInfo = v.(*fileInfoValue).value
} else {
fileInfo, err = c.fetchFileInfoMirror(id, path)
if err != nil {
return
}
}
if fileInfo.Size >= 0 {
mirror.FileInfo = &fileInfo
}
if clientInfo.GeoIPRecord != nil {
mirror.Distance = getDistanceKm(clientInfo.Latitude,
clientInfo.Longitude,
mirror.Latitude,
mirror.Longitude)
} else {
mirror.Distance = 0
}
mirrors = append(mirrors, mirror)
}
return
}
func (c *Cache) fetchFileMirrors(path string) (ids []string, err error) {
rconn := c.r.pool.Get()
defer rconn.Close()
ids, err = redis.Strings(rconn.Do("SMEMBERS", fmt.Sprintf("FILEMIRRORS_%s", path)))
if err != nil {
return
}
c.fmCache.Set(path, &fileMirrorValue{value: ids})
return
}
func (c *Cache) fetchMirror(mirrorID string) (mirror Mirror, err error) {
rconn := c.r.pool.Get()
defer rconn.Close()
reply, err := redis.Values(rconn.Do("HGETALL", fmt.Sprintf("MIRROR_%s", mirrorID)))
if err != nil {
return
}
if len(reply) == 0 {
err = redis.ErrNil
return
}
err = redis.ScanStruct(reply, &mirror)
if err != nil {
return
}
mirror.CountryFields = strings.Fields(mirror.CountryCodes)
c.mCache.Set(mirrorID, &mirrorValue{value: mirror})
return
}
func (c *Cache) fetchFileInfoMirror(id, path string) (fileInfo FileInfo, err error) {
rconn := c.r.pool.Get()
defer rconn.Close()
fileInfo.Size = -1
reply, err := redis.Values(rconn.Do("HGETALL", fmt.Sprintf("FILEINFO_%s_%s", id, path)))
if err != nil {
return
}
err = redis.ScanStruct(reply, &fileInfo)
if err != nil {
return
}
c.fimCache.Set(fmt.Sprintf("%s|%s", id, path), &fileInfoValue{value: fileInfo})
return
}
// GetMirror returns all information about a given mirror either from the cache
// or directly from the database if the object is not yet stored in the cache.
func (c *Cache) GetMirror(identifier string) (mirror Mirror, err error) {
v, ok := c.mCache.Get(identifier)
if ok {
mirror = v.(*mirrorValue).value
} else {
mirror, err = c.fetchMirror(identifier)
if err != nil {
return
}
}
return
}