Skip to content

Commit

Permalink
Fix address already in use with webhooks input during reload (#3206)
Browse files Browse the repository at this point in the history
  • Loading branch information
DanKans authored and danielnelson committed Sep 11, 2017
1 parent be83c8c commit f62e543
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions plugins/inputs/webhooks/webhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package webhooks
import (
"fmt"
"log"
"net"
"net/http"
"reflect"

Expand Down Expand Up @@ -33,6 +34,8 @@ type Webhooks struct {
Mandrill *mandrill.MandrillWebhook
Rollbar *rollbar.RollbarWebhook
Papertrail *papertrail.PapertrailWebhook

srv *http.Server
}

func NewWebhooks() *Webhooks {
Expand Down Expand Up @@ -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)
Expand All @@ -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")
}

0 comments on commit f62e543

Please sign in to comment.