...
1
16
17
18 package container
19
20 import (
21 "context"
22 "sync"
23 "time"
24 )
25
26
27 type RuntimeCache interface {
28 GetPods(context.Context) ([]*Pod, error)
29 ForceUpdateIfOlder(context.Context, time.Time) error
30 }
31
32 type podsGetter interface {
33 GetPods(context.Context, bool) ([]*Pod, error)
34 }
35
36
37 func NewRuntimeCache(getter podsGetter, cachePeriod time.Duration) (RuntimeCache, error) {
38 return &runtimeCache{
39 getter: getter,
40 cachePeriod: cachePeriod,
41 }, nil
42 }
43
44
45
46
47
48 type runtimeCache struct {
49 sync.Mutex
50
51 getter podsGetter
52
53 cachePeriod time.Duration
54
55 cacheTime time.Time
56
57 pods []*Pod
58 }
59
60
61
62 func (r *runtimeCache) GetPods(ctx context.Context) ([]*Pod, error) {
63 r.Lock()
64 defer r.Unlock()
65 if time.Since(r.cacheTime) > r.cachePeriod {
66 if err := r.updateCache(ctx); err != nil {
67 return nil, err
68 }
69 }
70 return r.pods, nil
71 }
72
73 func (r *runtimeCache) ForceUpdateIfOlder(ctx context.Context, minExpectedCacheTime time.Time) error {
74 r.Lock()
75 defer r.Unlock()
76 if r.cacheTime.Before(minExpectedCacheTime) {
77 return r.updateCache(ctx)
78 }
79 return nil
80 }
81
82 func (r *runtimeCache) updateCache(ctx context.Context) error {
83 pods, timestamp, err := r.getPodsWithTimestamp(ctx)
84 if err != nil {
85 return err
86 }
87 r.pods, r.cacheTime = pods, timestamp
88 return nil
89 }
90
91
92 func (r *runtimeCache) getPodsWithTimestamp(ctx context.Context) ([]*Pod, time.Time, error) {
93
94 timestamp := time.Now()
95 pods, err := r.getter.GetPods(ctx, false)
96 return pods, timestamp, err
97 }
98
View as plain text