-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache_manager.go
More file actions
476 lines (405 loc) · 11.5 KB
/
cache_manager.go
File metadata and controls
476 lines (405 loc) · 11.5 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package utils
import (
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// CacheManager handles cache clearing operations for repositories, release assets and lfs objects
type CacheManager struct {
repoCacheDir string
assetCacheDir string
lfsCacheDir string
repoMaxAge time.Duration
assetMaxAge time.Duration
lfsMaxAge time.Duration
repoMaxSize int64
assetMaxSize int64
lfsMaxSize int64
clearInterval time.Duration
stopChan chan struct{}
mu sync.Mutex
isRunning bool
}
// NewCacheManager creates a new cache manager with the specified configuration
func NewCacheManager() *CacheManager {
return &CacheManager{
repoCacheDir: viper.GetString("GIT_REPOS_DIR"),
assetCacheDir: viper.GetString("ATTACHMENT_DIR"),
lfsCacheDir: viper.GetString("LFS_OBJECTS_DIR"),
repoMaxAge: viper.GetDuration("CACHE_REPO_MAX_AGE"),
assetMaxAge: viper.GetDuration("CACHE_ASSET_MAX_AGE"),
lfsMaxAge: viper.GetDuration("CACHE_LFS_MAX_AGE"),
repoMaxSize: viper.GetInt64("CACHE_REPO_MAX_SIZE"),
assetMaxSize: viper.GetInt64("CACHE_ASSET_MAX_SIZE"),
lfsMaxSize: viper.GetInt64("CACHE_LFS_MAX_SIZE"),
clearInterval: viper.GetDuration("CACHE_CLEAR_INTERVAL"),
stopChan: make(chan struct{}),
}
}
// Start begins the cache clearing routine
func (cm *CacheManager) Start() error {
cm.mu.Lock()
if cm.isRunning {
cm.mu.Unlock()
return errors.New("cache manager is already running")
}
cm.isRunning = true
cm.mu.Unlock()
go cm.clearCacheRoutine()
return nil
}
// Stop halts the cache clearing routine
func (cm *CacheManager) Stop() {
cm.mu.Lock()
defer cm.mu.Unlock()
if !cm.isRunning {
return
}
close(cm.stopChan)
cm.isRunning = false
}
// clearCacheRoutine periodically clears the cache based on configured rules
func (cm *CacheManager) clearCacheRoutine() {
ticker := time.NewTicker(cm.clearInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := cm.clearCache(); err != nil {
LogError("cache-clear", fmt.Errorf("failed to clear cache: %v", err))
}
case <-cm.stopChan:
return
}
}
}
// clearCache performs the actual cache clearing operation
func (cm *CacheManager) clearCache() error {
// Clear repository cache
if err := cm.clearRepositoryCache(); err != nil {
return errors.Wrap(err, "failed to clear repository cache")
}
// Clear asset cache
if err := cm.clearAssetCache(); err != nil {
return errors.Wrap(err, "failed to clear asset cache")
}
// Clear LFS cache
if err := cm.clearLfsCache(); err != nil {
return errors.Wrap(err, "failed to clear lfs cache")
}
return nil
}
// isRepositoryInUse checks if a repository is currently locked/in use
func (cm *CacheManager) isRepositoryInUse(repoID uint64) bool {
return IsRepositoryInUse(repoID)
}
// isAssetInUse checks if an asset is currently locked/in use
func (cm *CacheManager) isAssetInUse(sha string) bool {
return IsAssetInUse(sha)
}
// isLfsObjectInUse checks if an LFS object is currently locked/in use
func (cm *CacheManager) isLfsObjectInUse(oid string) bool {
return IsLFSObjectInUse(oid)
}
// clearRepositoryCache clears old repository caches based on age and size
func (cm *CacheManager) clearRepositoryCache() error {
entries, err := os.ReadDir(cm.repoCacheDir)
if err != nil {
return errors.Wrap(err, "failed to read repository cache directory")
}
var totalSize int64
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// Extract repository ID from directory name
repoIDStr := strings.TrimSuffix(entry.Name(), ".git")
repoID, err := strconv.ParseUint(repoIDStr, 10, 64)
if err != nil {
LogError("cache-clear", fmt.Errorf("invalid repository ID in directory name %s: %v", entry.Name(), err))
continue
}
// Skip if repository is in use
if cm.isRepositoryInUse(repoID) {
logrus.WithFields(logrus.Fields{
"repo_id": repoID,
}).Info("skipping cache clear for in-use repository")
continue
}
repoPath := filepath.Join(cm.repoCacheDir, entry.Name())
info, err := entry.Info()
if err != nil {
LogError("cache-clear", fmt.Errorf("failed to get info for %s: %v", repoPath, err))
continue
}
// Check age
if time.Since(info.ModTime()) > cm.repoMaxAge {
if err := os.RemoveAll(repoPath); err != nil {
LogError("cache-clear", fmt.Errorf("failed to remove old repository %s: %v", repoPath, err))
} else {
logrus.WithFields(logrus.Fields{
"path": repoPath,
"age": time.Since(info.ModTime()),
}).Info("cleared old repository cache")
}
continue
}
// Calculate size
size, err := cm.calculateDirSize(repoPath)
if err != nil {
LogError("cache-clear", fmt.Errorf("failed to calculate size for %s: %v", repoPath, err))
continue
}
totalSize += size
}
// If total size exceeds max size, remove oldest entries
if totalSize > cm.repoMaxSize {
entries, err := os.ReadDir(cm.repoCacheDir)
if err != nil {
return errors.Wrap(err, "failed to read repository cache directory")
}
// Sort entries by modification time
type entryInfo struct {
path string
modTime time.Time
size int64
repoID uint64
}
var sortedEntries []entryInfo
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// Extract repository ID from directory name
repoIDStr := strings.TrimSuffix(entry.Name(), ".git")
repoID, err := strconv.ParseUint(repoIDStr, 10, 64)
if err != nil {
continue
}
// Skip if repository is in use
if cm.isRepositoryInUse(repoID) {
continue
}
repoPath := filepath.Join(cm.repoCacheDir, entry.Name())
info, err := entry.Info()
if err != nil {
continue
}
size, err := cm.calculateDirSize(repoPath)
if err != nil {
continue
}
sortedEntries = append(sortedEntries, entryInfo{
path: repoPath,
modTime: info.ModTime(),
size: size,
repoID: repoID,
})
}
// Sort by modification time (oldest first)
sort.Slice(sortedEntries, func(i, j int) bool {
return sortedEntries[i].modTime.Before(sortedEntries[j].modTime)
})
// Remove oldest entries until we're under the size limit
for _, entry := range sortedEntries {
if totalSize <= cm.repoMaxSize {
break
}
if err := os.RemoveAll(entry.path); err != nil {
LogError("cache-clear", fmt.Errorf("failed to remove repository %s: %v", entry.path, err))
continue
}
totalSize -= entry.size
logrus.WithFields(logrus.Fields{
"path": entry.path,
"size": entry.size,
}).Info("cleared repository cache due to size limit")
}
}
return nil
}
// clearLfsCache clears old LFS object caches based on age and size
func (cm *CacheManager) clearLfsCache() error {
entries, err := os.ReadDir(cm.lfsCacheDir)
if err != nil {
return errors.Wrap(err, "failed to read lfs cache directory")
}
var totalSize int64
for _, entry := range entries {
if entry.IsDir() {
continue
}
oid := entry.Name()
// Skip if LFS object is in use
if cm.isLfsObjectInUse(oid) {
logrus.WithFields(logrus.Fields{
"oid": oid,
}).Info("skipping cache clear for in-use lfs object")
continue
}
assetPath := filepath.Join(cm.lfsCacheDir, entry.Name())
info, err := entry.Info()
if err != nil {
LogError("cache-clear", fmt.Errorf("failed to get info for lfs object %s: %v", entry.Name(), err))
continue
}
// Remove if older than max age
if time.Since(info.ModTime()) > cm.lfsMaxAge {
if err := os.Remove(assetPath); err != nil {
LogError("cache-clear", fmt.Errorf("failed to remove old lfs object %s: %v", entry.Name(), err))
}
continue
}
totalSize += info.Size()
}
// If total size exceeds max size, remove oldest assets until size is within limit
if totalSize > cm.lfsMaxSize {
// Sort entries by modification time (oldest first)
sort.Slice(entries, func(i, j int) bool {
iInfo, iErr := entries[i].Info()
jInfo, jErr := entries[j].Info()
if iErr != nil || jErr != nil {
return false
}
return iInfo.ModTime().Before(jInfo.ModTime())
})
for _, entry := range entries {
if totalSize <= cm.lfsMaxSize {
break
}
if entry.IsDir() {
continue
}
oid := entry.Name()
// Skip if LFS object is in use
if cm.isLfsObjectInUse(oid) {
continue
}
assetPath := filepath.Join(cm.lfsCacheDir, entry.Name())
info, err := entry.Info()
if err != nil {
continue // Should have been caught earlier
}
if err := os.Remove(assetPath); err != nil {
LogError("cache-clear", fmt.Errorf("failed to remove lfs object %s for size limit: %v", entry.Name(), err))
} else {
totalSize -= info.Size()
}
}
}
return nil
}
// clearAssetCache clears old asset caches based on age and size
func (cm *CacheManager) clearAssetCache() error {
entries, err := os.ReadDir(cm.assetCacheDir)
if err != nil {
return errors.Wrap(err, "failed to read asset cache directory")
}
var totalSize int64
for _, entry := range entries {
if entry.IsDir() {
continue
}
// Skip if asset is in use
if cm.isAssetInUse(entry.Name()) {
logrus.WithFields(logrus.Fields{
"asset": entry.Name(),
}).Info("skipping cache clear for in-use asset")
continue
}
assetPath := filepath.Join(cm.assetCacheDir, entry.Name())
info, err := entry.Info()
if err != nil {
LogError("cache-clear", fmt.Errorf("failed to get info for %s: %v", assetPath, err))
continue
}
// Check age
if time.Since(info.ModTime()) > cm.assetMaxAge {
if err := os.Remove(assetPath); err != nil {
LogError("cache-clear", fmt.Errorf("failed to remove old asset %s: %v", assetPath, err))
} else {
logrus.WithFields(logrus.Fields{
"path": assetPath,
"age": time.Since(info.ModTime()),
}).Info("cleared old asset cache")
}
continue
}
totalSize += info.Size()
}
// If total size exceeds max size, remove oldest entries
if totalSize > cm.assetMaxSize {
entries, err := os.ReadDir(cm.assetCacheDir)
if err != nil {
return errors.Wrap(err, "failed to read asset cache directory")
}
// Sort entries by modification time
type entryInfo struct {
path string
modTime time.Time
size int64
}
var sortedEntries []entryInfo
for _, entry := range entries {
if entry.IsDir() {
continue
}
// Skip if asset is in use
if cm.isAssetInUse(entry.Name()) {
continue
}
assetPath := filepath.Join(cm.assetCacheDir, entry.Name())
info, err := entry.Info()
if err != nil {
continue
}
sortedEntries = append(sortedEntries, entryInfo{
path: assetPath,
modTime: info.ModTime(),
size: info.Size(),
})
}
// Sort by modification time (oldest first)
sort.Slice(sortedEntries, func(i, j int) bool {
return sortedEntries[i].modTime.Before(sortedEntries[j].modTime)
})
// Remove oldest entries until we're under the size limit
for _, entry := range sortedEntries {
if totalSize <= cm.assetMaxSize {
break
}
if err := os.Remove(entry.path); err != nil {
LogError("cache-clear", fmt.Errorf("failed to remove asset %s: %v", entry.path, err))
continue
}
totalSize -= entry.size
logrus.WithFields(logrus.Fields{
"path": entry.path,
"size": entry.size,
}).Info("cleared asset cache due to size limit")
}
}
return nil
}
// calculateDirSize calculates the total size of a directory
func (cm *CacheManager) calculateDirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return nil
})
return size, err
}