Skip to content

Commit

Permalink
Use workers instead spawning goroutines for each incoming DNS request
Browse files Browse the repository at this point in the history
  • Loading branch information
Uladzimir Trehubenka committed Nov 27, 2017
1 parent 9fc4eb2 commit f7e4c4c
Show file tree
Hide file tree
Showing 2 changed files with 223 additions and 112 deletions.
90 changes: 90 additions & 0 deletions benchmark_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package dns

import (
"fmt"
"net"
"sync"
"testing"
"time"
)

func BenchmarkServer(b *testing.B) {
HandleFunc(".", erraticHandler)
defer HandleRemove(".")
for _, i := range []int{0, 50, 100, 200, 1000} {
benchmark(i, b)
}
}

func benchmark(workers int, b *testing.B) {
s, addr, err := runLocalUDPServer(workers)
if err != nil {
b.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()

m := new(Msg)
m.SetQuestion("domain.local.", TypeA)

test := fmt.Sprintf("%d_workers", workers)
b.Run(test, func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := Exchange(m, addr)
if err != nil {
b.Fatalf("Exchange() failed: %v", err)
}
}
})
}

var (
rrA, _ = NewRR(". IN 0 A 192.0.2.53")
rrAAAA, _ = NewRR(". IN 0 AAAA 2001:DB8::53")
)

func erraticHandler(w ResponseWriter, r *Msg) {
r.Response = true

switch r.Question[0].Qtype {
case TypeA:
rr := *(rrA.(*A))
rr.Header().Name = r.Question[0].Name
r.Answer = []RR{&rr}
r.Rcode = RcodeSuccess
case TypeAAAA:
rr := *(rrAAAA.(*AAAA))
rr.Header().Name = r.Question[0].Name
r.Answer = []RR{&rr}
r.Rcode = RcodeSuccess
default:
r.Rcode = RcodeServerFailure
}

w.WriteMsg(r)
}

func runLocalUDPServer(workers int) (*Server, string, error) {
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
return nil, "", err
}

var wg sync.WaitGroup
wg.Add(1)
server := &Server{
PacketConn: pc,
ReadTimeout: time.Hour,
WriteTimeout: time.Hour,
NotifyStartedFunc: wg.Done,
Handler: DefaultServeMux,
Workers: workers,
}

go func() {
server.ActivateAndServe()
pc.Close()
}()

wg.Wait()
return server, pc.LocalAddr().String(), nil
}
Loading

0 comments on commit f7e4c4c

Please sign in to comment.