Fix address already in use with webhooks input during reload (#3206)

This commit is contained in:
DanKans 2017-09-11 19:51:45 +01:00 committed by Daniel Nelson
parent be83c8c8f0
commit f62e543003
1 changed files with 28 additions and 14 deletions

View File

@ -3,6 +3,7 @@ package webhooks
import (
"fmt"
"log"
"net"
"net/http"
"reflect"
@ -33,6 +34,8 @@ type Webhooks struct {
Mandrill *mandrill.MandrillWebhook
Rollbar *rollbar.RollbarWebhook
Papertrail *papertrail.PapertrailWebhook
srv *http.Server
}
func NewWebhooks() *Webhooks {
@ -70,19 +73,6 @@ func (wb *Webhooks) Gather(_ telegraf.Accumulator) error {
return nil
}
func (wb *Webhooks) Listen(acc telegraf.Accumulator) {
r := mux.NewRouter()
for _, webhook := range wb.AvailableWebhooks() {
webhook.Register(r, acc)
}
err := http.ListenAndServe(fmt.Sprintf("%s", wb.ServiceAddress), r)
if err != nil {
acc.AddError(fmt.Errorf("E! Error starting server: %v", err))
}
}
// Looks for fields which implement Webhook interface
func (wb *Webhooks) AvailableWebhooks() []Webhook {
webhooks := make([]Webhook, 0)
@ -105,11 +95,35 @@ func (wb *Webhooks) AvailableWebhooks() []Webhook {
}
func (wb *Webhooks) Start(acc telegraf.Accumulator) error {
go wb.Listen(acc)
r := mux.NewRouter()
for _, webhook := range wb.AvailableWebhooks() {
webhook.Register(r, acc)
}
wb.srv = &http.Server{Handler: r}
ln, err := net.Listen("tcp", fmt.Sprintf("%s", wb.ServiceAddress))
if err != nil {
log.Fatalf("E! Error starting server: %v", err)
return err
}
go func() {
if err := wb.srv.Serve(ln); err != nil {
if err != http.ErrServerClosed {
acc.AddError(fmt.Errorf("E! Error listening: %v", err))
}
}
}()
log.Printf("I! Started the webhooks service on %s\n", wb.ServiceAddress)
return nil
}
func (rb *Webhooks) Stop() {
rb.srv.Close()
log.Println("I! Stopping the Webhooks service")
}