Merge pull request #1 from mvrilo/master

Atmoic map missing locks
This commit is contained in:
kenshin 2014-01-08 07:34:10 -08:00
commit 5a8883419b
2 changed files with 18 additions and 3 deletions

View File

@ -6,6 +6,7 @@ import (
"fmt"
"github.com/hoisie/redis"
"github.com/miekg/dns"
"sync"
"time"
)
@ -56,11 +57,13 @@ type MemoryCache struct {
Backend map[string]Mesg
Expire time.Duration
Maxcount int
mu *sync.RWMutex
}
func (c *MemoryCache) Get(key string) (*dns.Msg, error) {
c.mu.RLock()
mesg, ok := c.Backend[key]
c.mu.RUnlock()
if !ok {
return nil, KeyNotFound{key}
}
@ -81,20 +84,28 @@ func (c *MemoryCache) Set(key string, msg *dns.Msg) error {
expire := time.Now().Add(c.Expire)
mesg := Mesg{msg, expire}
c.mu.Lock()
c.Backend[key] = mesg
c.mu.Unlock()
return nil
}
func (c *MemoryCache) Remove(key string) {
c.mu.RLock()
delete(c.Backend, key)
c.mu.RUnlock()
}
func (c *MemoryCache) Exists(key string) bool {
c.mu.RLock()
_, ok := c.Backend[key]
c.mu.RUnlock()
return ok
}
func (c *MemoryCache) Length() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.Backend)
}

View File

@ -3,6 +3,7 @@ package main
import (
"github.com/miekg/dns"
"net"
"sync"
"time"
)
@ -20,6 +21,7 @@ type GODNSHandler struct {
resolver *Resolver
cache Cache
hosts Hosts
mu *sync.Mutex
}
func NewHandler() *GODNSHandler {
@ -48,6 +50,7 @@ func NewHandler() *GODNSHandler {
Backend: make(map[string]Mesg),
Expire: time.Duration(cacheConfig.Expire) * time.Second,
Maxcount: cacheConfig.Maxcount,
mu: new(sync.RWMutex),
}
case "redis":
// cache = &MemoryCache{
@ -64,11 +67,10 @@ func NewHandler() *GODNSHandler {
hosts := NewHosts(settings.Hosts, settings.Redis)
return &GODNSHandler{resolver, cache, hosts}
return &GODNSHandler{resolver, cache, hosts, new(sync.Mutex)}
}
func (h *GODNSHandler) do(Net string, w dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0]
Q := Question{UnFqdn(q.Name), dns.TypeToString[q.Qtype], dns.ClassToString[q.Qclass]}
@ -97,8 +99,10 @@ func (h *GODNSHandler) do(Net string, w dns.ResponseWriter, req *dns.Msg) {
Debug("%s didn't hit cache: %s", Q.String(), err)
} else {
Debug("%s hit cache", Q.String())
h.mu.Lock()
mesg.Id = req.Id
w.WriteMsg(mesg)
h.mu.Unlock()
return
}