forked from MarshallWace/cachenator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
163 lines (137 loc) · 4.47 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
// Copyright 2021 Adrian Chifor, Marshall Wace
// SPDX-FileCopyrightText: 2021 Marshall Wace <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only
package main
import (
"context"
"fmt"
"strings"
"time"
"github.com/adrianchifor/go-parallel"
"github.com/aws/aws-sdk-go/aws"
"github.com/gin-gonic/gin"
"github.com/mailgun/groupcache/v2"
log "github.com/sirupsen/logrus"
)
var (
peers []string
cacheGroup *groupcache.Group
cachePool *groupcache.HTTPPool
maxCacheSize int64
ttl int
timeout int
)
func initCachePool() {
cachePool = groupcache.NewHTTPPoolOpts(fmt.Sprintf("http://%s:%d", host, port),
&groupcache.HTTPPoolOptions{})
if len(peers) > 0 {
cachePool.Set(peers...)
}
cacheGroup = groupcache.NewGroup("s3", maxCacheSize<<20, groupcache.GetterFunc(cacheFiller))
}
func cacheFiller(ctx context.Context, cacheKey string, dest groupcache.Sink) error {
log.Debugf("Pulling '%s' into cache from S3", cacheKey)
keySplit := strings.Split(cacheKey, "#")
bucket := keySplit[0]
key := keySplit[1]
buf := aws.NewWriteAtBuffer([]byte{})
err := s3Download(bucket, key, buf)
if err != nil {
log.Errorf("Failed to download '%s' from S3: %v", cacheKey, err)
return err
}
log.Debugf("Pulled '%s' into buffer, adding to cache with TTL %dm", cacheKey, ttl)
err = dest.SetBytes(buf.Bytes(), time.Now().Add(time.Minute*time.Duration(ttl)))
if err != nil {
log.Errorf("Failed to fill cache sink with '%s': %v", key, err)
return err
}
log.Debugf("Pulled '%s' into cache", cacheKey)
return nil
}
func cacheGet(c *gin.Context) {
bucket := strings.TrimSpace(c.Query("bucket"))
if bucket == "" {
c.String(400, "'bucket' not found in querystring parameters")
return
}
key := strings.TrimSpace(c.Query("key"))
if key == "" {
c.String(400, "'key' not found in querystring parameters")
return
}
cacheKey := constructCacheKey(bucket, key)
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cancel()
log.Debugf("Checking cache for '%s'", cacheKey)
var cacheView groupcache.ByteView
if err := cacheGroup.Get(ctx, cacheKey, groupcache.ByteViewSink(&cacheView)); err != nil {
c.String(404, fmt.Sprintf("Blob '%s' not found", cacheKey))
return
}
extraHeaders := map[string]string{
"Content-Disposition": fmt.Sprintf(`attachment; filename="%s"`, key),
}
log.Debugf("Sending '%s' bytes in response", cacheKey)
c.DataFromReader(200, int64(cacheView.Len()), "application/octet-stream", cacheView.Reader(), extraHeaders)
}
func cachePrewarm(c *gin.Context) {
bucket := strings.TrimSpace(c.Query("bucket"))
if bucket == "" {
c.String(400, "'bucket' not found in querystring parameters")
return
}
prefix := strings.TrimSpace(c.Query("prefix"))
if prefix == "" {
c.String(400, "'prefix' not found in querystring parameters")
return
}
log.Debugf("Pre-warming cache with prefix '%s#%s'", bucket, prefix)
keys, err := s3ListKeys(bucket, prefix)
if err != nil {
msg := fmt.Sprintf("Failed to list keys with prefix '%s' in S3 bucket '%s': %v", prefix, bucket, err)
log.Errorf(msg)
c.String(500, msg)
return
}
if len(keys) == 0 {
c.String(404, fmt.Sprintf("No keys found with prefix '%s' in S3 bucket '%s'", prefix, bucket))
return
}
go func() {
getPool := parallel.SmallJobPool()
defer getPool.Close()
for _, key := range keys {
key := key
// Prewarm 10 keys at a time
getPool.AddJob(func() {
cacheKey := constructCacheKey(bucket, key)
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cancel()
log.Debugf("Pre-warming cache with key '%s'", key)
var tmpCacheView groupcache.ByteView
if err := cacheGroup.Get(ctx, cacheKey, groupcache.ByteViewSink(&tmpCacheView)); err != nil {
log.Errorf("Failed to pre-warm cache with key '%s': %v", cacheKey, err)
}
})
}
}()
c.String(200, fmt.Sprintf("Pre-warming cache in the background with prefix '%s' from S3 bucket '%s'", prefix, bucket))
}
func cacheInvalidate(c *gin.Context) {
bucket := strings.TrimSpace(c.Query("bucket"))
if bucket == "" {
c.String(400, "'bucket' not found in querystring parameters")
return
}
key := strings.TrimSpace(c.Query("key"))
if key == "" {
c.String(400, "'key' not found in querystring parameters")
return
}
cacheKey := constructCacheKey(bucket, key)
cacheGroup.Remove(context.Background(), cacheKey)
msg := fmt.Sprintf("'%s' invalidated from cache", cacheKey)
log.Debugf(msg)
c.String(200, msg)
}