Debian Codegraph @

mirrors/cache.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package mirrors
5
6 import (
7 "fmt"
8 "strconv"
9 "strings"
10 "time"
11 "unsafe"
12
13 "github.com/etix/mirrorbits/database"
14 "github.com/etix/mirrorbits/filesystem"
15 "github.com/etix/mirrorbits/network"
16 "github.com/etix/mirrorbits/utils"
17 "github.com/gomodule/redigo/redis"
18 )
19
20 // Cache implements a local caching mechanism of type LRU for content available in the
21 // redis database that is automatically invalidated if the object is updated in Redis.
22 type Cache struct {
23 r *database.Redis
24 fiCache *LRUCache
25 fmCache *LRUCache
26 mCache *LRUCache
27 fimCache *LRUCache
28
29 mirrorUpdateEvent chan string
30 fileUpdateEvent chan string
31 mirrorFileUpdateEvent chan string
32 pubsubReconnectedEvent chan string
33 invalidationEvent chan string
34 }
35
36 type fileInfoValue struct {
37 value filesystem.FileInfo
38 }
39
40 func (f *fileInfoValue) Size() int {
41 return int(unsafe.Sizeof(f.value))
42 }
43
44 type fileMirrorValue struct {
45 value []int
46 }
47
48 func (f *fileMirrorValue) Size() int {
49 return cap(f.value)
50 }
51
52 type mirrorValue struct {
53 value Mirror
54 }
55
56 func (f *mirrorValue) Size() int {
57 return int(unsafe.Sizeof(f.value))
58 }
59
60 // NewCache constructs a new instance of Cache
61 func NewCache(r *database.Redis) *Cache {
62 if r == nil || r.Pubsub == nil {
63 return nil
64 }
65
66 c := &Cache{
67 r: r,
68 }
69
70 // Create the LRU
71 c.fiCache = NewLRUCache(1024000)
72 c.fmCache = NewLRUCache(2048000)
73 c.mCache = NewLRUCache(1024000)
74 c.fimCache = NewLRUCache(4096000)
75
76 // Create event channels
77 c.mirrorUpdateEvent = make(chan string, 10)
78 c.fileUpdateEvent = make(chan string, 10)
79 c.mirrorFileUpdateEvent = make(chan string, 10)
80 c.pubsubReconnectedEvent = make(chan string)
81
82 c.invalidationEvent = make(chan string, 10)
83
84 // Subscribe to events
85 c.r.Pubsub.SubscribeEvent(database.MIRROR_UPDATE, c.mirrorUpdateEvent)
86 c.r.Pubsub.SubscribeEvent(database.FILE_UPDATE, c.fileUpdateEvent)
87 c.r.Pubsub.SubscribeEvent(database.MIRROR_FILE_UPDATE, c.mirrorFileUpdateEvent)
88 c.r.Pubsub.SubscribeEvent(database.PUBSUB_RECONNECTED, c.pubsubReconnectedEvent)
89
90 go func() {
91 for {
92 //FIXME add a close channel
93 select {
94 case data := <-c.mirrorUpdateEvent:
95 c.mCache.Delete(data)
96 select {
97 case c.invalidationEvent <- data:
98 default:
99 // Non-blocking
100 }
101 case data := <-c.fileUpdateEvent:
102 c.fiCache.Delete(data)
103 case data := <-c.mirrorFileUpdateEvent:
104 s := strings.SplitN(data, " ", 2)
105 c.fmCache.Delete(s[1])
106 c.fimCache.Delete(fmt.Sprintf("%s|%s", s[0], s[1]))
107 case <-c.pubsubReconnectedEvent:
108 c.Clear()
109 }
110 }
111 }()
112
113 return c
114 }
115
116 // Clear clears the local cache
117 func (c *Cache) Clear() {
118 c.fiCache.Clear()
119 c.fmCache.Clear()
120 c.mCache.Clear()
121 c.fimCache.Clear()
122 }
123
124 // GetMirrorInvalidationEvent returns a channel that contains ID of mirrors
125 // that have just been invalidated. This function is supposed to have only
126 // ONE reader and is made to avoid a race for MIRROR_UPDATE events between
127 // a mirror invalidation and a mirror being fetched from the cache.
128 func (c *Cache) GetMirrorInvalidationEvent() <-chan string {
129 return c.invalidationEvent
130 }
131
132 // GetFileInfo returns file information for a given file either from the cache
133 // or directly from the database if the object is not yet stored in the cache.
134 func (c *Cache) GetFileInfo(path string) (f filesystem.FileInfo, err error) {
135 v, ok := c.fiCache.Get(path)
136 if ok {
137 f = v.(*fileInfoValue).value
138 } else {
139 f, err = c.fetchFileInfo(path)
140 }
141 return
142 }
143
144 func (c *Cache) fetchFileInfo(path string) (f filesystem.FileInfo, err error) {
145 rconn := c.r.Get()
146 defer rconn.Close()
147 f.Path = path // Path is not stored in the object instance in redis
148
149 reply, err := redis.Strings(rconn.Do("HMGET", fmt.Sprintf("FILE_%s", path), "size", "modTime", "sha1", "sha256", "md5"))
150 if err != nil {
151 return
152 }
153
154 f.Size, _ = strconv.ParseInt(reply[0], 10, 64)
155 f.ModTime, _ = time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", reply[1])
156 f.Sha1 = reply[2]
157 f.Sha256 = reply[3]
158 f.Md5 = reply[4]
159 c.fiCache.Set(path, &fileInfoValue{value: f})
160 return
161 }
162
163 // GetMirrors returns all the mirrors serving a given file either from the cache
164 // or directly from the database if the object is not yet stored in the cache.
165 func (c *Cache) GetMirrors(path string, clientInfo network.GeoIPRecord) (mirrors []Mirror, err error) {
166 var mirrorsIDs []int
167 v, ok := c.fmCache.Get(path)
168 if ok {
169 mirrorsIDs = v.(*fileMirrorValue).value
170 } else {
171 mirrorsIDs, err = c.fetchFileMirrors(path)
172 if err != nil {
173 return
174 }
175 }
176 mirrors = make([]Mirror, 0, len(mirrorsIDs))
177 for _, id := range mirrorsIDs {
178 var mirror Mirror
179 var fileInfo filesystem.FileInfo
180 v, ok := c.mCache.Get(strconv.Itoa(id))
181 if ok {
182 mirror = v.(*mirrorValue).value
183 } else {
184 //TODO execute missing items in a MULTI query
185 mirror, err = c.fetchMirror(id)
186 if err != nil {
187 return
188 }
189 }
190 v, ok = c.fimCache.Get(fmt.Sprintf("%d|%s", id, path))
191 if ok {
192 fileInfo = v.(*fileInfoValue).value
193 } else {
194 fileInfo, err = c.fetchFileInfoMirror(id, path)
195 if err != nil {
196 return
197 }
198 }
199 if fileInfo.Size >= 0 {
200 mirror.FileInfo = &fileInfo
201 }
202
203 // Add the path in the results so we can access it from the templates
204 mirror.FileInfo.Path = path
205
206 if clientInfo.IsValid() {
207 mirror.Distance = utils.GetDistanceKm(clientInfo.Latitude,
208 clientInfo.Longitude,
209 mirror.Latitude,
210 mirror.Longitude)
211 } else {
212 mirror.Distance = 0
213 }
214 mirrors = append(mirrors, mirror)
215 }
216 return
217 }
218
219 func (c *Cache) fetchFileMirrors(path string) (ids []int, err error) {
220 rconn := c.r.Get()
221 defer rconn.Close()
222 ids, err = redis.Ints(rconn.Do("SMEMBERS", fmt.Sprintf("FILEMIRRORS_%s", path)))
223 if err != nil {
224 return
225 }
226 c.fmCache.Set(path, &fileMirrorValue{value: ids})
227 return
228 }
229
230 func (c *Cache) fetchMirror(mirrorID int) (mirror Mirror, err error) {
231 rconn := c.r.Get()
232 defer rconn.Close()
233 reply, err := redis.Values(rconn.Do("HGETALL", fmt.Sprintf("MIRROR_%d", mirrorID)))
234 if err != nil {
235 return
236 }
237 if len(reply) == 0 {
238 err = redis.ErrNil
239 return
240 }
241 err = redis.ScanStruct(reply, &mirror)
242 if err != nil {
243 return
244 }
245 mirror.Prepare()
246 c.mCache.Set(strconv.Itoa(mirrorID), &mirrorValue{value: mirror})
247 return
248 }
249
250 func (c *Cache) GetFileInfoMirror(mirrorID int, path string) (f filesystem.FileInfo, err error) {
251 var fileInfo filesystem.FileInfo
252
253 v, ok := c.fimCache.Get(fmt.Sprintf("%d|%s", mirrorID, path))
254 if ok {
255 fileInfo = v.(*fileInfoValue).value
256 } else {
257 fileInfo, err = c.fetchFileInfoMirror(mirrorID, path)
258 if err != nil {
259 return
260 }
261 }
262 return fileInfo, nil
263 }
264
265 func (c *Cache) fetchFileInfoMirror(id int, path string) (f filesystem.FileInfo, err error) {
266 rconn := c.r.Get()
267 defer rconn.Close()
268 f.Path = path // Path is not stored in the object instance in redis
269
270 reply, err := redis.Strings(rconn.Do("HMGET", fmt.Sprintf("FILEINFO_%d_%s", id, path), "size", "modTime", "sha1", "sha256", "md5"))
271 if err != nil {
272 return
273 }
274
275 // Note: as of today, only the size is stored by the scanners
276 // all other fields are left blank.
277
278 f.Size, _ = strconv.ParseInt(reply[0], 10, 64)
279 f.ModTime, _ = time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", reply[1])
280 f.Sha1 = reply[2]
281 f.Sha256 = reply[3]
282 f.Md5 = reply[4]
283
284 c.fimCache.Set(fmt.Sprintf("%d|%s", id, path), &fileInfoValue{value: f})
285 return
286 }
287
288 // GetMirror returns all information about a given mirror either from the cache
289 // or directly from the database if the object is not yet stored in the cache.
290 func (c *Cache) GetMirror(id int) (mirror Mirror, err error) {
291 v, ok := c.mCache.Get(strconv.Itoa(id))
292 if ok {
293 mirror = v.(*mirrorValue).value
294 } else {
295 mirror, err = c.fetchMirror(id)
296 if err != nil {
297 return
298 }
299 }
300 return
301 }