Repository navigation
Expand file tree
/
Copy pathcache.go
More file actions
279 lines (233 loc) · 7.25 KB
/
Copy pathcache.go
File metadata and controls
279 lines (233 loc) · 7.25 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
/*
File: cache.go
Version: 2.57.0 (Split)
Last Updated: 04-Nov-2026 19:38 CET
Description:
High-performance, sharded, non-blocking DNS cache core for sdproxy.
Manages memory allocation, cryptographic sharding (HashDoS protection),
and asynchronous garbage collection (Sweeper).
Hot-path Read/Write operations have been moved to cache_rw.go.
Disk persistence has been moved to cache_persistence.go.
UI introspection has been moved to cache_ui.go.
Changes:
2.57.0 - [FIX] Emitted startup `InitCache` summary and `persist_save_interval`
warnings when `logSystem` or `logCaching` is active so Simple Logging
Mode (`logSimple: true`) retains startup messages and warnings.
2.56.0 - [SECURITY/FIX] Kept `runSweeper` active when `serveStaleInfinite` is
enabled so expired synthetic responses (`v.routeName == ""`, such as
policy blocks and local-identity records) are still garbage-collected
while upstream responses (`v.routeName != ""`) are retained for
emergency stale fallback.
2.55.0 - [SECURITY/FIX] Added `BypassPolicies` and `BypassLocal` to `DNSCacheKey`
and `getShard` hashing.
2.54.0 - [SECURITY/FIX] Added RecursionDesired to cache partitioning and shard hashing.
2.53.0 - [PERF] Eliminated significant Garbage Collection (GC) thrashing
within the `runSweeper` background routine.
2.52.0 - [CLEANUP] Simplified `storeItem` mutex orchestration organically
via `defer` declarations.
2.51.0 - [PERF/FIX] Eliminated the cache-hot-path repack caused by
`answer_sort: round-robin`.
*/
package main
import (
"hash/maphash"
"log"
"sync"
"sync/atomic"
"time"
)
type DNSCacheKey struct {
Name string
ClientName string
ECS string
Qtype uint16
Qclass uint16
RouteIdx uint16
DoBit bool
CdBit bool
BypassGlobal bool
BypassPolicies bool
BypassLocal bool
RecursionDesired bool
}
type cacheItem struct {
packed atomic.Pointer[[]byte]
expireNano int64
staleNano int64
cachedAtNano int64
routeName string
hits atomic.Uint32
prefetched atomic.Bool
rotation atomic.Uint32
}
type cacheShard struct {
sync.RWMutex
items map[DNSCacheKey]*cacheItem
}
const shardCount = 32
var shards [shardCount]*cacheShard
var cacheMaxPerShard int
var cacheHashSeed maphash.Seed
// ---------------------------------------------------------------------------
// Startup feature flags — set once in InitCache, read on every hot-path call.
// ---------------------------------------------------------------------------
var hasPrefetch bool
var staleEnabled bool
var cacheUpstreamNeg bool
var cacheRotateAnswers bool
var serveStaleInfinite bool
var cacheSynthFlag bool
var cacheLocalIdentity bool
// ---------------------------------------------------------------------------
// Initialisation
// ---------------------------------------------------------------------------
func InitCache(maxSize int, _ int) {
if !cfg.Cache.Enabled {
return
}
cacheHashSeed = maphash.MakeSeed()
for i := range shards {
shards[i] = &cacheShard{items: make(map[DNSCacheKey]*cacheItem)}
}
cacheMaxPerShard = maxSize / shardCount
if cacheMaxPerShard < 1 {
cacheMaxPerShard = 1
}
hasPrefetch = cfg.Cache.PrefetchBefore > 0 && cfg.Cache.PrefetchMinHits > 0
staleEnabled = cfg.Cache.StaleTTL > 0
cacheUpstreamNeg = cfg.Cache.CacheUpstreamNegative
cacheSynthFlag = cfg.Cache.CacheSynthetic
cacheLocalIdentity = cfg.Cache.CacheLocalIdentity
serveStaleInfinite = cfg.Cache.ServeStaleInfinite
cacheRotateAnswers = cfg.Cache.AnswerSort == "round-robin"
sweepInterval := 60 * time.Second
if cfg.Cache.SweepIntervalS > 0 {
sweepInterval = time.Duration(cfg.Cache.SweepIntervalS) * time.Second
}
if logCaching || logSystem {
log.Printf("[CACHE] Initialised: size=%d shards=%d sweep=%s stale=%ds "+
"prefetch=%ds/%dhits synth=%v localid=%v upneg=%v sort=%s inf_stale=%v persist=%v",
maxSize, shardCount, sweepInterval,
cfg.Cache.StaleTTL, cfg.Cache.PrefetchBefore, cfg.Cache.PrefetchMinHits,
cacheSynthFlag, cacheLocalIdentity, cacheUpstreamNeg, cfg.Cache.AnswerSort, serveStaleInfinite, cfg.Cache.Persist)
}
go runSweeper(sweepInterval)
if cfg.Cache.Persist {
LoadCache()
if cfg.Cache.PersistSaveInterval != "" && cfg.Cache.PersistSaveInterval != "0" && cfg.Cache.PersistSaveInterval != "0s" {
if interval, err := time.ParseDuration(cfg.Cache.PersistSaveInterval); err == nil && interval > 0 {
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
SaveCache()
case <-shutdownCh:
return
}
}
}()
} else if logCaching || logSystem {
log.Printf("[CACHE] WARNING: Invalid persist_save_interval %q: %v", cfg.Cache.PersistSaveInterval, err)
}
}
}
}
func runSweeper(interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
toDelete := make([]DNSCacheKey, 0, max(cacheMaxPerShard/4, 16))
for {
select {
case <-ticker.C:
now := time.Now().UnixNano()
for i := range shards {
shard := shards[i]
toDelete = toDelete[:0]
shard.RLock()
for k, v := range shard.items {
if now >= v.staleNano && (!serveStaleInfinite || v.routeName == "") {
toDelete = append(toDelete, k)
}
}
shard.RUnlock()
if len(toDelete) == 0 {
continue
}
shard.Lock()
for _, k := range toDelete {
if v, ok := shard.items[k]; ok && now >= v.staleNano && (!serveStaleInfinite || v.routeName == "") {
delete(shard.items, k)
}
}
shard.Unlock()
}
case <-shutdownCh:
return
}
}
}
// ---------------------------------------------------------------------------
// Shard selector
// ---------------------------------------------------------------------------
func getShard(key DNSCacheKey) *cacheShard {
h := maphash.String(cacheHashSeed, key.Name)
if key.ClientName != "" {
h ^= maphash.String(cacheHashSeed, key.ClientName) * 0x5bd1e9955bd1e995
}
if key.ECS != "" {
h ^= maphash.String(cacheHashSeed, key.ECS) * 0x9e3779b97f4a7c15
}
mix := uint64(key.Qtype)<<32 | uint64(key.Qclass)<<16 | uint64(key.RouteIdx)
if key.DoBit {
mix |= 1 << 48
}
if key.CdBit {
mix |= 1 << 49
}
if key.BypassGlobal {
mix |= 1 << 50
}
if key.RecursionDesired {
mix |= 1 << 51
}
if key.BypassPolicies {
mix |= 1 << 52
}
if key.BypassLocal {
mix |= 1 << 53
}
h ^= mix
h ^= h >> 32
h ^= h >> 16
h ^= h >> 8
h ^= h >> 4
return shards[h&(shardCount-1)]
}
// ---------------------------------------------------------------------------
// Internal store helper
// ---------------------------------------------------------------------------
const evictionSampleSize = 8
func storeItem(key DNSCacheKey, item *cacheItem) {
shard := getShard(key)
shard.Lock()
defer shard.Unlock()
if _, exists := shard.items[key]; !exists && len(shard.items) >= cacheMaxPerShard {
var victim DNSCacheKey
var victimStale int64
var sampled int
for k, v := range shard.items {
if sampled == 0 || v.staleNano < victimStale {
victim = k
victimStale = v.staleNano
}
sampled++
if sampled >= evictionSampleSize {
break
}
}
delete(shard.items, victim)
}
shard.items[key] = item
}