Debian Codegraph @

cache/cache.go

raw
1 // Package cache
2 //
3 // Implement client side caching for client.Client. This is useful for burst-happy applications that will try to query
4 // a lot of the same information in small chunks.
5 //
6 // For example, an application could try to check the state of nodes, but do so using one request per node. This is
7 // obviously not ideal in larger cluster, where it would be more efficient to request the state of all nodes at once.
8 // Depending on the application, this may not be possible, however.
9 //
10 // This package contains ready-to-use client side caches with configurable duration and automatic invalidation under the
11 // assumption that modifications are made from the same client.
12 package cache
13
14 import (
15 "fmt"
16 "strings"
17 "sync"
18 "time"
19
20 log "github.com/sirupsen/logrus"
21
22 "github.com/LINBIT/golinstor/client"
23 )
24
25 var (
26 yes = true
27 cacheOpt = &client.ListOpts{Cached: &yes}
28 )
29
30 type Cache interface {
31 apply(c *client.Client)
32 }
33
34 // WithCaches sets up the given caches on the client.Client.
35 func WithCaches(caches ...Cache) client.Option {
36 return func(cl *client.Client) error {
37 for _, ca := range caches {
38 ca.apply(cl)
39 }
40
41 return nil
42 }
43 }
44
45 type cache struct {
46 mu sync.Mutex
47 lastUpdate time.Time
48 cache any
49 }
50
51 // Invalidate forcefully resets the cache.
52 // The next call to Get will always invoke the provided function.
53 func (c *cache) Invalidate() {
54 c.mu.Lock()
55 c.lastUpdate = time.Time{}
56 c.cache = nil
57 c.mu.Unlock()
58 }
59
60 // Get returns a cached response or the result of the provided update function.
61 //
62 // If the cache is current, it will return the last successful cached response.
63 // If the cache is outdated, it will run the provided function to retrieve a result. A successful response
64 // is cached for later use.
65 func (c *cache) Get(timeout time.Duration, updateFunc func() (any, error)) (any, error) {
66 c.mu.Lock()
67 defer c.mu.Unlock()
68
69 now := time.Now()
70
71 if timeout != 0 && c.lastUpdate.Add(timeout).Before(now) {
72 result, err := updateFunc()
73 if err != nil {
74 return nil, err
75 }
76
77 c.cache = result
78 c.lastUpdate = now
79 }
80
81 return c.cache, nil
82 }
83
84 // filterNodeAndPoolOpts filters generic items based on the provided client.ListOpts
85 // This tries to mimic the behaviour of LINSTOR when using the node and storage pool query parameters.
86 func filterNodeAndPoolOpts[T Filterable](items []T, opts ...*client.ListOpts) []T {
87 filterNodes := make(map[string]struct{})
88 filterPools := make(map[string]struct{})
89 var filterProps []string
90
91 if hasUnsupportedOpts(opts...) {
92 log.WithField("opts", opts).Warn("unsupported filter opts in cache")
93 }
94
95 for _, o := range opts {
96 for _, n := range o.Node {
97 filterNodes[n] = struct{}{}
98 }
99
100 for _, sp := range o.StoragePool {
101 filterPools[sp] = struct{}{}
102 }
103
104 filterProps = append(filterProps, o.Prop...)
105 }
106
107 var result []T
108
109 outer:
110 for i := range items {
111 if len(filterNodes) > 0 {
112 if !anyMatches(filterNodes, nodes(&items[i])) {
113 continue
114 }
115 }
116
117 if len(filterPools) > 0 {
118 if !anyMatches(filterPools, pools(&items[i])) {
119 continue
120 }
121 }
122
123 itemProps := props(&items[i])
124 for _, filterProp := range filterProps {
125 key, val, found := strings.Cut(filterProp, "=")
126 itemVal, ok := itemProps[key]
127 if !ok {
128 continue outer
129 }
130
131 if found && val != itemVal {
132 continue outer
133 }
134 }
135
136 result = append(result, items[i])
137 }
138
139 return result
140 }
141
142 func hasUnsupportedOpts(opts ...*client.ListOpts) bool {
143 for _, opt := range opts {
144 if len(opt.Snapshots) > 0 || len(opt.Resource) > 0 || opt.Limit != 0 || opt.Offset != 0 {
145 return true
146 }
147 }
148 return false
149 }
150
151 type Filterable interface {
152 client.Node | client.StoragePool | client.ResourceWithVolumes | client.Snapshot | client.PhysicalStorageViewItem
153 }
154
155 func anyMatches(haystack map[string]struct{}, items []string) bool {
156 for _, item := range items {
157 if _, ok := haystack[item]; ok {
158 return true
159 }
160 }
161
162 return false
163 }
164
165 func nodes(item any) []string {
166 switch item := item.(type) {
167 case *client.Node:
168 return []string{item.Name}
169 case *client.StoragePool:
170 return []string{item.NodeName}
171 case *client.ResourceWithVolumes:
172 return []string{item.NodeName}
173 case *client.Snapshot:
174 return item.Nodes
175 case *client.PhysicalStorageViewItem:
176 var result []string
177 for k := range item.Nodes {
178 result = append(result, k)
179 }
180 return result
181 default:
182 panic(fmt.Sprintf("unsupported item type: %T", item))
183 }
184 }
185
186 func pools(item any) []string {
187 switch item := item.(type) {
188 case *client.Node:
189 return nil
190 case *client.StoragePool:
191 return []string{item.StoragePoolName}
192 case *client.ResourceWithVolumes:
193 var result []string
194 for _, vol := range item.Volumes {
195 result = append(result, vol.StoragePoolName)
196 }
197 return result
198 case *client.Snapshot:
199 return nil
200 case *client.PhysicalStorageViewItem:
201 return nil
202
203 default:
204 panic(fmt.Sprintf("unsupported item type: %T", item))
205
206 }
207 }
208
209 func props(item any) map[string]string {
210 switch item := item.(type) {
211 case *client.Node:
212 return item.Props
213 case *client.StoragePool:
214 return item.Props
215 case *client.ResourceWithVolumes:
216 return item.Props
217 case *client.Snapshot:
218 return item.Props
219 case *client.PhysicalStorageViewItem:
220 return nil
221 default:
222 panic(fmt.Sprintf("unsupported item type: %T", item))
223 }
224 }