Close the UDP connection in Stop() of statsd input plugin.

If not, when doing reload, we may listen to the same port, we'll get
error about listen to already used address.
This commit is contained in:
HUANG Wei 2016-03-17 16:10:36 +08:00
parent 530b4f3bee
commit f4c2977cb5
1 changed files with 10 additions and 5 deletions

View File

@ -65,6 +65,8 @@ type Statsd struct {
// bucket -> influx templates // bucket -> influx templates
Templates []string Templates []string
listener *net.UDPConn
} }
func NewStatsd() *Statsd { func NewStatsd() *Statsd {
@ -246,13 +248,14 @@ func (s *Statsd) Start(_ telegraf.Accumulator) error {
// udpListen starts listening for udp packets on the configured port. // udpListen starts listening for udp packets on the configured port.
func (s *Statsd) udpListen() error { func (s *Statsd) udpListen() error {
var err error
address, _ := net.ResolveUDPAddr("udp", s.ServiceAddress) address, _ := net.ResolveUDPAddr("udp", s.ServiceAddress)
listener, err := net.ListenUDP("udp", address) s.listener, err = net.ListenUDP("udp", address)
if err != nil { if err != nil {
log.Fatalf("ERROR: ListenUDP - %s", err) log.Fatalf("ERROR: ListenUDP - %s", err)
} }
defer listener.Close() defer s.listener.Close()
log.Println("Statsd listener listening on: ", listener.LocalAddr().String()) log.Println("Statsd listener listening on: ", s.listener.LocalAddr().String())
for { for {
select { select {
@ -260,9 +263,10 @@ func (s *Statsd) udpListen() error {
return nil return nil
default: default:
buf := make([]byte, s.UDPPacketSize) buf := make([]byte, s.UDPPacketSize)
n, _, err := listener.ReadFromUDP(buf) n, _, err := s.listener.ReadFromUDP(buf)
if err != nil { if err != nil {
log.Printf("ERROR: %s\n", err.Error()) log.Printf("ERROR READ: %s\n", err.Error())
continue
} }
select { select {
@ -557,6 +561,7 @@ func (s *Statsd) Stop() {
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
log.Println("Stopping the statsd service") log.Println("Stopping the statsd service")
s.listener.Close()
close(s.done) close(s.done)
close(s.in) close(s.in)
} }