diff options
author | Martin Polden <mpolden@mpolden.no> | 2020-01-12 00:04:23 +0100 |
---|---|---|
committer | Martin Polden <mpolden@mpolden.no> | 2020-01-12 00:04:23 +0100 |
commit | 8f942b848ee4ed8cc06bdfe7107b3358cee0e39b (patch) | |
tree | 5671d2e0db805323d629a9e9bdbe443dd8a58672 /cache | |
parent | 6e9697ef071fceeae3fc9d1fe024034717fd47a2 (diff) |
Add cache metrics
Diffstat (limited to 'cache')
-rw-r--r-- | cache/cache.go | 16 | ||||
-rw-r--r-- | cache/cache_test.go | 12 |
2 files changed, 28 insertions, 0 deletions
diff --git a/cache/cache.go b/cache/cache.go index a0218b0..beaa5a1 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -47,6 +47,12 @@ type Value struct { msg *dns.Msg } +// Stats contains cache statistics. +type Stats struct { + Size int + Capacity int +} + // Rcode returns the response code of the cached value v. func (v *Value) Rcode() int { return v.msg.Rcode } @@ -228,6 +234,16 @@ func (c *Cache) Set(key uint32, msg *dns.Msg) { c.set(key, msg) } +// Stats returns cache statistics. +func (c *Cache) Stats() Stats { + c.mu.RLock() + defer c.mu.RUnlock() + return Stats{ + Capacity: c.capacity, + Size: len(c.values), + } +} + func (c *Cache) set(key uint32, msg *dns.Msg) bool { return c.setValue(Value{Key: key, CreatedAt: c.now(), msg: msg}) } diff --git a/cache/cache_test.go b/cache/cache_test.go index 346df25..e571f73 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -453,6 +453,18 @@ func TestCacheWithBackend(t *testing.T) { } } +func TestCacheStats(t *testing.T) { + c := New(10, nil) + msg := newA("example.com.", 60, net.ParseIP("192.0.2.1")) + c.Set(1, msg) + c.Set(2, msg) + want := Stats{Capacity: 10, Size: 2} + got := c.Stats() + if !reflect.DeepEqual(got, want) { + t.Errorf("Stats() = %+v, want %+v", got, want) + } +} + func BenchmarkNewKey(b *testing.B) { for n := 0; n < b.N; n++ { NewKey("key", 1, 1) |