/
caching_boltdb.go
363 lines (312 loc) · 8.05 KB
/
caching_boltdb.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package caching
import (
"errors"
"fmt"
"sync"
"time"
"github.com/boltdb/bolt"
"github.com/cloudfoundry-community/firehose-to-syslog/logging"
cfclient "github.com/cloudfoundry-community/go-cfclient"
json "github.com/mailru/easyjson"
rate "go.uber.org/ratelimit"
)
const (
APP_BUCKET = "AppBucket"
)
type CachingBoltConfig struct {
Path string
IgnoreMissingApps bool
CacheInvalidateTTL time.Duration
RequestBySec int
}
type CachingBolt struct {
appClient AppClient
appdb *bolt.DB
lock sync.RWMutex
cache map[string]*App
missingApps map[string]struct{}
closing chan struct{}
wg sync.WaitGroup
config *CachingBoltConfig
}
func NewCachingBolt(client AppClient, config *CachingBoltConfig) (*CachingBolt, error) {
return &CachingBolt{
appClient: client,
cache: make(map[string]*App),
missingApps: make(map[string]struct{}),
closing: make(chan struct{}),
config: config,
}, nil
}
func (c *CachingBolt) Open() error {
// Open bolt db
db, err := bolt.Open(c.config.Path, 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
logging.LogError("Fail to open boltdb: ", err)
return err
}
c.appdb = db
if err := c.createBucket(); err != nil {
logging.LogError("Fail to create bucket: ", err)
return err
}
if c.config.CacheInvalidateTTL != time.Duration(0) {
c.invalidateCache()
}
return c.populateCache()
}
func (c *CachingBolt) populateCache() error {
apps, err := c.getAllAppsFromBoltDB()
if err != nil {
return err
}
if len(apps) == 0 {
// populate from remote
apps, err = c.getAllAppsFromRemote()
if err != nil {
return err
}
}
c.cache = apps
return nil
}
func (c *CachingBolt) Close() error {
close(c.closing)
// Wait for background goroutine exit
c.wg.Wait()
return c.appdb.Close()
}
// GetAppInfo tries first get app info from cache. If caches doesn't have this
// app info (cache miss), it issues API to retrieve the app info from remote
// if the app is not already missing and clients don't ignore the missing app
// info, and then add the app info to the cache
// On the other hand, if the app is already missing and clients want to
// save remote API and ignore missing app, then a nil app info and an error
// will be returned.
func (c *CachingBolt) GetApp(appGuid string) (*App, error) {
app, err := c.getAppFromCache(appGuid)
if err != nil {
return nil, err
}
// Find in cache
if app != nil {
return app, nil
}
// First time seeing app
app, err = c.getAppFromRemote(appGuid)
if err != nil {
if c.config.IgnoreMissingApps {
// Record this missing app
c.lock.Lock()
c.missingApps[appGuid] = struct{}{}
c.lock.Unlock()
}
return nil, err
}
// Add to in-memory cache
c.lock.Lock()
c.cache[app.Guid] = app
c.lock.Unlock()
return app, nil
}
// GetAllApps returns all apps info
func (c *CachingBolt) GetAllApps() (map[string]*App, error) {
c.lock.RLock()
apps := make(map[string]*App, len(c.cache))
for _, app := range c.cache {
dup := *app
apps[dup.Guid] = &dup
}
c.lock.RUnlock()
return apps, nil
}
func (c *CachingBolt) getAppFromCache(appGuid string) (*App, error) {
c.lock.RLock()
if app, ok := c.cache[appGuid]; ok {
// in in-memory cache
c.lock.RUnlock()
return app, nil
}
_, alreadyMissed := c.missingApps[appGuid]
if c.config.IgnoreMissingApps && alreadyMissed {
// already missed
c.lock.RUnlock()
return nil, errors.New("App was missed and ignored")
}
c.lock.RUnlock()
// Didn't find in cache and it is not missed or we are not ignoring missed app
return nil, nil
}
func (c *CachingBolt) getAllAppsFromBoltDB() (map[string]*App, error) {
apps := make(map[string]*App)
err := c.appdb.View(func(tx *bolt.Tx) error {
return tx.Bucket([]byte(APP_BUCKET)).ForEach(func(guid []byte, v []byte) error {
var app App
err := json.Unmarshal(v, &app)
if err != nil {
return err
}
apps[app.Guid] = &app
return nil
})
})
if err != nil {
return nil, err
}
return apps, nil
}
func (c *CachingBolt) createBucket() error {
return c.appdb.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(APP_BUCKET))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
}
// invalidateCache perodically fetches a full copy apps info from remote
// and update boltdb and in-memory cache
func (c *CachingBolt) invalidateCache() {
ticker := time.NewTicker(c.config.CacheInvalidateTTL)
c.wg.Add(1)
go func() {
defer c.wg.Done()
for {
select {
case <-ticker.C:
// continue
apps, err := c.getAllAppsFromRemote()
if err == nil {
c.lock.Lock()
c.cache = apps
c.lock.Unlock()
}
case <-c.closing:
return
}
}
}()
}
func (c *CachingBolt) addRecord(app *App) {
c.appdb.Update(func(tx *bolt.Tx) error {
serialize, err := json.Marshal(app)
if err != nil {
return fmt.Errorf("Error Marshaling data: %s", err)
}
b := tx.Bucket([]byte(APP_BUCKET))
if err := b.Put([]byte(app.Guid), serialize); err != nil {
return fmt.Errorf("Error inserting data: %s", err)
}
return nil
})
}
func (c *CachingBolt) fillDatabase(apps map[string]*App) {
for _, app := range apps {
c.addRecord(app)
}
}
func (c *CachingBolt) fromPCFApp(app *cfclient.App) *App {
return &App{
app.Name,
app.Guid,
app.SpaceData.Entity.Name,
app.SpaceData.Entity.Guid,
app.SpaceData.Entity.OrgData.Entity.Name,
app.SpaceData.Entity.OrgData.Entity.Guid,
c.isOptOut(app.Environment),
}
}
func (c *CachingBolt) getAppFromRemote(appGuid string) (*App, error) {
cfApp, err := c.appClient.GetAppByGuidNoInlineCall(appGuid)
if err != nil {
return nil, err
}
app := c.fromPCFApp(&cfApp)
c.addRecord(app)
return app, nil
}
func (c *CachingBolt) isOptOut(envVar map[string]interface{}) bool {
if val, ok := envVar["F2S_DISABLE_LOGGING"]; ok && val == "true" {
return true
}
return false
}
//Inspired by cf exporter
func (c *CachingBolt) getAllAppsFromRemote() (map[string]*App, error) {
logging.LogStd("Retrieving Apps from Remote ...", false)
apps := make(map[string]*App)
// Listing Orgs
organizations, err := c.appClient.ListOrgs()
if err != nil {
logging.LogError("Error while listing organization: %v", err)
return apps, err
}
var wg = &sync.WaitGroup{}
//Adding Global Rate limitings 50sec
rl := rate.New(c.config.RequestBySec, rate.WithoutSlack)
for _, organization := range organizations {
wg.Add(1)
go func(organization cfclient.Org, rl rate.Limiter) {
defer wg.Done()
rl.Take()
err := c.getOrgSpaces(&organization, rl)
if err != nil {
logging.LogError("Error gettings Org", err)
}
}(organization, rl)
}
wg.Wait()
logging.LogStd(fmt.Sprintf("Found [%d] Apps!", len(apps)), false)
apps, err = c.getAllAppsFromBoltDB()
if err != nil {
logging.LogError("Error while gettings all apps from BoltDB: %v", err)
return apps, err
}
return apps, nil
}
func (c *CachingBolt) getOrgSpaces(organization *cfclient.Org, l rate.Limiter) error {
spaces, err := c.appClient.OrgSpaces(organization.Guid)
if err != nil {
logging.LogError("Error while listing spaces for organization `%s`: %v", err)
return err
}
var wg = &sync.WaitGroup{}
errChannel := make(chan error, len(spaces))
for _, space := range spaces {
wg.Add(1)
go func(space cfclient.Space) {
defer wg.Done()
l.Take()
err := c.getSpaceSummary(organization, &space)
if err != nil {
errChannel <- err
}
}(space)
}
wg.Wait()
close(errChannel)
return <-errChannel
}
func (c *CachingBolt) getSpaceSummary(organization *cfclient.Org, space *cfclient.Space) error {
spaceSummary, err := space.Summary()
if err != nil {
logging.LogError("Error while getting summary for space `%s`: %v", err)
return err
}
for _, application := range spaceSummary.Apps {
app := c.fromPCFAppSummary(&application, organization, space)
c.addRecord(app)
}
return nil
}
func (c *CachingBolt) fromPCFAppSummary(app *cfclient.AppSummary, organization *cfclient.Org, space *cfclient.Space) *App {
return &App{
app.Name,
app.Guid,
space.Name,
space.Guid,
organization.Name,
organization.Guid,
c.isOptOut(app.Environment),
}
}