forked from square/keywhiz-fs
/
cache.go
254 lines (226 loc) · 7.34 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
// Copyright 2015 Square Inc.
//
// 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 keywhizfs
import (
"time"
"github.com/square/keywhiz-fs/log"
)
// SecretBackend represents an interface for storing secrets.
type SecretBackend interface {
Secret(string) (secret *Secret, ok bool)
SecretList() (secretList []Secret, ok bool)
}
// Timeouts contains configuration for timeouts:
// timeout_backend_deadline: optimistic timeout to wait for cache
// timeout_max_wait: timeout for client to get data from server
type Timeouts struct {
// FUSE may make many lookups in quick succession. If cached data is recent within the threshold,
// a backend request is not attempted.
Fresh time.Duration
// BackendDeadline is distinct from the backend timeout. It is an optimistic timeout to wait
// until resorting to cached data.
BackendDeadline time.Duration
MaxWait time.Duration
}
// Cache contains necessary state to return secrets, using previously cached content or retrieving
// from a server if necessary.
type Cache struct {
*log.Logger
secretMap *SecretMap
backend SecretBackend
timeouts Timeouts
}
// NewCache initializes a Cache.
func NewCache(backend SecretBackend, timeouts Timeouts, logConfig log.Config) *Cache {
logger := log.New("kwfs_cache", logConfig)
return &Cache{logger, NewSecretMap(), backend, timeouts}
}
// Clear empties the internal cache.
func (c *Cache) Clear() {
c.Infof("Cache cleared")
c.secretMap = NewSecretMap()
}
// Secret retrieves a Secret by name from cache or a server.
//
// Cache logic:
// * If cache hit and very recent: return cache entry
// * Ask backend w/ timeout
// * If backend returns fast: update cache, return
// * If timeout_backend_deadline AND cache hit: return cache entry, background update cache when
// backend returns
// * If timeout_max_wait: log error and pretend file doesn't exist
func (c *Cache) Secret(name string) (*Secret, bool) {
failureDeadline := time.After(c.timeouts.MaxWait)
var backendDeadline <-chan time.Time // inactive, until backend request starts
var cachedSecret *Secret
resultFromCache := func() (*Secret, bool) {
success := cachedSecret != nil
return cachedSecret, success
}
cacheDone := c.cacheSecret(name)
var backendDone chan *Secret
for {
select {
case s := <-backendDone:
backendDone = nil
if s != nil { // Always return successful value from backend
return s, true
}
// Backend failed and cache lookup already finished
if cacheDone == nil {
return resultFromCache()
}
case s := <-cacheDone:
cacheDone = nil
if s != nil {
cachedSecret = &s.Secret
// If cache entry very recent, return cache result
if time.Since(s.Time) < c.timeouts.Fresh {
return resultFromCache()
}
}
// Start backend request and wait until optimistic deadline
backendDone = c.backendSecret(name)
backendDeadline = time.After(c.timeouts.BackendDeadline)
case <-backendDeadline:
if cachedSecret != nil {
return cachedSecret, true
}
case <-failureDeadline:
c.Errorf("Cache and backend timeout: %v", name)
return nil, false
}
}
}
// SecretList returns a listing of Secrets from cache or a server.
//
// Cache logic:
// * Ask backend w/ timeout
// * If backend returns fast: update cache, return
// * If timeout_backend_deadline: return cache entries, background update cache when
// backend returns
// * If timeout_max_wait: log error and pretend no files
func (c *Cache) SecretList() []Secret {
failureDeadline := time.After(c.timeouts.MaxWait)
// Optimistically wait for a backend response before using a cached response.
backendDeadline := time.After(c.timeouts.BackendDeadline)
cacheDone := c.cacheSecretList()
backendDone := c.backendSecretList()
var cachedSecrets []Secret
for {
select {
case secrets := <-backendDone:
return secrets
case cachedSecrets = <-cacheDone:
cacheDone = nil
case <-backendDeadline:
if cachedSecrets != nil {
return cachedSecrets
}
case <-failureDeadline:
c.Errorf("Cache and backend timeout: secretList()")
return make([]Secret, 0)
}
}
}
// Add inserts a secret into the cache. If a secret is already in the cache with a matching
// identifier, it will be overridden This method is most useful for testing since lookups
// may add data to the cache.
func (c *Cache) Add(s Secret) {
c.secretMap.Put(s.Name, s)
}
// Len returns the number of values stored in the cache. This method is most useful for testing.
func (c *Cache) Len() int {
return c.secretMap.Len()
}
// cacheSecret retrieves a secret from the cache.
//
// Cache lookup may block, so retrieval is concurrent and a channel is returned to communicate a
// successful value. The channel will not be fulfilled on error.
func (c *Cache) cacheSecret(name string) chan *SecretTime {
secretc := make(chan *SecretTime, 1)
go func() {
defer close(secretc)
secret, ok := c.secretMap.Get(name)
if ok && len(secret.Secret.Content) > 0 {
c.Debugf("Cache hit: %v", name)
secretc <- &secret
} else {
c.Debugf("Cache miss: %v", name)
secretc <- nil
}
}()
return secretc
}
// cacheSecretList retrieves a secret listing from the cache.
//
// Cache lookup may block, so retrieval is concurrent and a channel is returned to communicate
// a cache lookup result.
func (c *Cache) cacheSecretList() chan []Secret {
secretsc := make(chan []Secret, 1)
go func() {
defer close(secretsc)
values := c.secretMap.Values()
secrets := make([]Secret, len(values))
for i, v := range values {
secrets[i] = v.Secret
}
secretsc <- secrets
}()
return secretsc
}
// backendSecret retrieves a secret from the backend and updates the cache.
//
// Retrieval is concurrent, so a channel is returned to communicate a successful value. The channel
// will not be fulfilled on error.
func (c *Cache) backendSecret(name string) chan *Secret {
secretc := make(chan *Secret)
go func() {
defer close(secretc)
secret, ok := c.backend.Secret(name)
if !ok {
secretc <- nil
return
}
secretc <- secret
c.secretMap.Put(name, *secret)
}()
return secretc
}
// backendSecretList retrieves a secret listing from the backend and updates the cache.
//
// Retrieval is concurrent, so a channel is returned to communicate successful values. The channel
// will not be fulfilled on error.
func (c *Cache) backendSecretList() chan []Secret {
secretsc := make(chan []Secret, 1)
go func() {
secrets, ok := c.backend.SecretList()
if !ok {
return
}
secretsc <- secrets
close(secretsc)
newMap := NewSecretMap()
for _, backendSecret := range secrets {
// If the cache contains a secret with content, keep it over backendSecret.
if s, ok := c.secretMap.Get(backendSecret.Name); ok && len(s.Secret.Content) > 0 {
newMap.Put(backendSecret.Name, s.Secret)
} else { // Otherwise, cache the latest information.
newMap.Put(backendSecret.Name, backendSecret)
}
}
c.secretMap.Overwrite(newMap)
}()
return secretsc
}