grafana/pkg/services/notifications/webhook.go
Santiago 4b1af6fb06
Fix empty contact point URLs when template parsing fails (#47029)
* fix empty URLs

* leave URL templating, use fallback

* better fix, new tests cases

* fix linting errors
2022-03-31 15:57:48 -03:00

102 lines
2.4 KiB
Go

package notifications
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"time"
"golang.org/x/net/context/ctxhttp"
"github.com/grafana/grafana/pkg/util"
)
type Webhook struct {
Url string
User string
Password string
Body string
HttpMethod string
HttpHeader map[string]string
ContentType string
}
var netTransport = &http.Transport{
TLSClientConfig: &tls.Config{
Renegotiation: tls.RenegotiateFreelyAsClient,
},
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
var netClient = &http.Client{
Timeout: time.Second * 30,
Transport: netTransport,
}
func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
if webhook.HttpMethod == "" {
webhook.HttpMethod = http.MethodPost
}
ns.log.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod)
if webhook.HttpMethod != http.MethodPost && webhook.HttpMethod != http.MethodPut {
return fmt.Errorf("webhook only supports HTTP methods PUT or POST")
}
request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
if err != nil {
return err
}
if webhook.ContentType == "" {
webhook.ContentType = "application/json"
}
request.Header.Set("Content-Type", webhook.ContentType)
request.Header.Set("User-Agent", "Grafana")
if webhook.User != "" && webhook.Password != "" {
request.Header.Set("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
}
for k, v := range webhook.HttpHeader {
request.Header.Set(k, v)
}
resp, err := ctxhttp.Do(ctx, netClient, request)
if err != nil {
return err
}
defer func() {
if err := resp.Body.Close(); err != nil {
ns.log.Warn("Failed to close response body", "err", err)
}
}()
if resp.StatusCode/100 == 2 {
ns.log.Debug("Webhook succeeded", "url", webhook.Url, "statuscode", resp.Status)
// flushing the body enables the transport to reuse the same connection
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
ns.log.Error("Failed to copy resp.Body to ioutil.Discard", "err", err)
}
return nil
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
ns.log.Debug("Webhook failed", "url", webhook.Url, "statuscode", resp.Status, "body", string(body))
return fmt.Errorf("Webhook response status %v", resp.Status)
}