2016-06-15 07:45:05 -05:00
|
|
|
package notifications
|
|
|
|
|
|
|
|
import (
|
2016-06-16 01:15:48 -05:00
|
|
|
"bytes"
|
2016-06-15 07:45:05 -05:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/grafana/grafana/pkg/log"
|
2016-06-16 01:15:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/util"
|
2016-06-15 07:45:05 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type Webhook struct {
|
2016-06-16 01:15:48 -05:00
|
|
|
Url string
|
|
|
|
User string
|
|
|
|
Password string
|
|
|
|
Body string
|
2016-06-15 07:45:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
var webhookQueue chan *Webhook
|
|
|
|
var webhookLog log.Logger
|
|
|
|
|
|
|
|
func initWebhookQueue() {
|
|
|
|
webhookLog = log.New("notifications.webhook")
|
|
|
|
webhookQueue = make(chan *Webhook, 10)
|
|
|
|
go processWebhookQueue()
|
|
|
|
}
|
|
|
|
|
|
|
|
func processWebhookQueue() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case webhook := <-webhookQueue:
|
|
|
|
err := sendWebRequest(webhook)
|
|
|
|
|
|
|
|
if err != nil {
|
2016-06-16 01:56:19 -05:00
|
|
|
webhookLog.Error("Failed to send webrequest ", "error", err)
|
2016-06-15 07:45:05 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func sendWebRequest(webhook *Webhook) error {
|
2016-06-16 01:15:48 -05:00
|
|
|
client := http.Client{
|
|
|
|
Timeout: time.Duration(3 * time.Second),
|
|
|
|
}
|
2016-06-15 07:45:05 -05:00
|
|
|
|
2016-06-16 01:15:48 -05:00
|
|
|
request, err := http.NewRequest("POST", webhook.Url, bytes.NewReader([]byte(webhook.Body)))
|
|
|
|
if webhook.User != "" && webhook.Password != "" {
|
|
|
|
request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
|
|
|
|
}
|
2016-06-15 07:45:05 -05:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := client.Do(request)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var addToWebhookQueue = func(msg *Webhook) {
|
|
|
|
webhookQueue <- msg
|
|
|
|
}
|