forked from cloudfoundry-community/firehose-to-syslog
/
caching_lazyfill.go
272 lines (235 loc) · 6.79 KB
/
caching_lazyfill.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
package caching
import (
"encoding/json"
"fmt"
"math/rand"
"strings"
"time"
uuid "github.com/satori/go.uuid"
)
type entity struct {
Name string `json:"name"`
SpaceGUID string `json:"space_guid"`
OrganizationGUID string `json:"organization_guid"`
Environment map[string]interface{} `json:"environment_json"`
TTL time.Time
}
func (e *entity) appIsOptOut() bool {
return e.Environment["F2S_DISABLE_LOGGING"] == "true"
}
type CacheLazyFillConfig struct {
// IgnoreMissingApps no error if an app can't be found
IgnoreMissingApps bool
// CacheInvalidateTTL is the approx TTL for cached data. Code will randomly pick between 0.75x and 1.2
CacheInvalidateTTL time.Duration
StripAppSuffixes []string
}
type CacheLazyFill struct {
client CFSimpleClient
store CacheStore
config *CacheLazyFillConfig
}
func NewCacheLazyFill(client CFSimpleClient, store CacheStore, config *CacheLazyFillConfig) *CacheLazyFill {
return &CacheLazyFill{
client: client,
store: store,
config: config,
}
}
// FillCache communicates with the server to enumerate *all* applications and fills
// the cache
func (c *CacheLazyFill) FillCache() error {
allApps, err := c.fetchEntityListFromAPI("apps")
if err != nil {
return err
}
// Populate bolt with all apps
for guid, app := range allApps {
// Canonicalise the guid
u, err := uuid.FromString(guid)
if err != nil {
return err
}
uuid := u.String()
// Save our app out
err = c.normaliseAndSaveEntityToDatabase("apps", uuid, app)
if err != nil {
return err
}
// Fetch and poulate space and org
_, _, err = c.getSpaceAndOrg(app.SpaceGUID)
if err != nil {
return err
}
}
return nil
}
// getEntity looks up the entity in the cache, and if not found, or TTL expired, fetches from the server
// entityType *must* be checked for safety by caller
// guid will be validated as a guid by this function
// apps are treated specially, in that if IgnoreMissingApps is set, then an error will result in an empty object returned.
// Also for apps, we will strip anything that matches StripAppSuffixes from the name before storing.
func (c *CacheLazyFill) getEntity(entityType, guid string) (*entity, error) {
// Canonicalise guid
u, err := uuid.FromString(guid)
if err != nil {
return nil, err
}
uuid := u.String()
// Check if we have it already
var rv entity
err = c.store.Get(makeCacheStorageKey(entityType, uuid), &rv)
switch err {
case nil:
if rv.TTL.After(time.Now()) {
return &rv, nil
}
// else continue
case ErrKeyNotFound:
// continue
default:
return nil, err
}
// Fetch from remote
nv, err := c.fetchEntityFromAPI(entityType, uuid)
if err != nil {
if entityType == "apps" && c.config.IgnoreMissingApps {
nv = &entity{}
} else {
return nil, err
}
}
// Save it out
err = c.normaliseAndSaveEntityToDatabase(entityType, uuid, nv)
if err != nil {
return nil, err
}
return nv, nil
}
// makeCacheStorageKey returns the key for the entity in the bolt bucket
// entityType is "apps" or "spaces" or "orgs" - caller must validate
// uuid must be validated by caller
func makeCacheStorageKey(entityType, uuid string) string {
return fmt.Sprintf("%s/%s", entityType, uuid)
}
// normaliseAndSaveEntityToDatabase saves the entity to the cache, stripping app name prefixes if enabled
// entityType is "apps" or "spaces" or "orgs" - caller must validate
// uuid must be validated by caller
// nv may be modified by this function
func (c *CacheLazyFill) normaliseAndSaveEntityToDatabase(entityType, uuid string, nv *entity) error {
// Strip name suffixes if applicable. This is intended for blue green deployments,
// so that things like -venerable can be stripped from renamed apps
if entityType == "apps" {
for _, suffix := range c.config.StripAppSuffixes {
if strings.HasSuffix(nv.Name, suffix) {
nv.Name = nv.Name[:len(nv.Name)-len(suffix)]
break
}
}
}
// Set TTL to value between 75% and 125% of desired amount. This is to spread out cache invalidations
nv.TTL = time.Now().Add(time.Duration(float64(c.config.CacheInvalidateTTL.Nanoseconds()) * (0.75 + (rand.Float64() / 2.0))))
// Write to DB
return c.store.Set(makeCacheStorageKey(entityType, uuid), nv)
}
// fetchEntityListFromAPI fetches a full list of all such entities from the server
// entityType must have been validated by the caller
func (c *CacheLazyFill) fetchEntityListFromAPI(entityType string) (map[string]*entity, error) {
url := fmt.Sprintf("/v2/%s?results-per-page=100", entityType)
rv := make(map[string]*entity)
for {
var md struct {
NextURL string `json:"next_url"`
Resources []*struct {
Metadata struct {
GUID string `json:"guid"`
} `json:"metadata"`
Entity *entity `json:"entity"`
} `json:"resources"`
}
err := c.makeRequestAndDecodeJSON(url, &md)
if err != nil {
return nil, err
}
for _, r := range md.Resources {
if r.Entity == nil {
return nil, fmt.Errorf("nil entity returned, URL: %s, GUID of nil resource: %s", url, r.Metadata.GUID)
}
rv[r.Metadata.GUID] = r.Entity
}
if md.NextURL == "" {
// we're done!
return rv, nil
}
url = md.NextURL
}
}
func (c *CacheLazyFill) makeRequestAndDecodeJSON(url string, rv interface{}) error {
resp, err := c.client.DoGet(url)
if err != nil {
return err
}
defer resp.Close()
err = json.NewDecoder(resp).Decode(rv)
if err != nil {
return err
}
return err
}
// both entityType and guid must have been validated by the caller
func (c *CacheLazyFill) fetchEntityFromAPI(entityType, guid string) (*entity, error) {
var md struct {
Entity *entity `json:"entity"`
}
url := fmt.Sprintf("/v2/%s/%s", entityType, guid)
err := c.makeRequestAndDecodeJSON(url, &md)
if err != nil {
return nil, err
}
if md.Entity == nil {
return nil, fmt.Errorf("nil entity returned, URL: %s", url)
}
return md.Entity, nil
}
func (c *CacheLazyFill) getSpaceAndOrg(spaceGuid string) (*entity, *entity, error) {
space, err := c.getEntity("spaces", spaceGuid)
if err != nil {
if c.config.IgnoreMissingApps {
space = &entity{}
} else {
return nil, nil, err
}
}
org, err := c.getEntity("organizations", space.OrganizationGUID)
if err != nil {
if c.config.IgnoreMissingApps {
org = &entity{}
} else {
return nil, nil, err
}
}
return space, org, nil
}
func (c *CacheLazyFill) GetApp(appGuid string) (*App, error) {
app, err := c.getEntity("apps", appGuid)
if err != nil {
if c.config.IgnoreMissingApps {
app = &entity{}
} else {
return nil, err
}
}
space, org, err := c.getSpaceAndOrg(app.SpaceGUID)
if err != nil {
return nil, err
}
return &App{
Guid: appGuid,
Name: app.Name,
SpaceGuid: app.SpaceGUID,
SpaceName: space.Name,
OrgGuid: space.OrganizationGUID,
OrgName: org.Name,
IgnoredApp: app.appIsOptOut(),
}, nil
}