Commit 64a7d8ce by Torkel Ödegaard Committed by GitHub

Merge pull request #15833 from grafana/15694_fix

fix discord notifier so it doesn't crash when there are no image generated
parents 878b41d6 f21c976b
...@@ -111,31 +111,52 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error { ...@@ -111,31 +111,52 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error {
json, _ := bodyJSON.MarshalJSON() json, _ := bodyJSON.MarshalJSON()
content_type := "application/json" cmd := &m.SendWebhookSync{
Url: this.WebhookURL,
var body []byte HttpMethod: "POST",
ContentType: "application/json",
if embeddedImage { }
var b bytes.Buffer if !embeddedImage {
cmd.Body = string(json)
} else {
err := this.embedImage(cmd, evalContext.ImageOnDiskPath, json)
if err != nil {
this.log.Error("failed to embed image", "error", err)
return err
}
}
w := multipart.NewWriter(&b) if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
this.log.Error("Failed to send notification to Discord", "error", err)
return err
}
f, err := os.Open(evalContext.ImageOnDiskPath) return nil
}
func (this *DiscordNotifier) embedImage(cmd *m.SendWebhookSync, imagePath string, existingJSONBody []byte) error {
f, err := os.Open(imagePath)
defer f.Close()
if err != nil { if err != nil {
this.log.Error("Can't open graph file", err) if os.IsNotExist(err) {
cmd.Body = string(existingJSONBody)
return nil
}
if !os.IsNotExist(err) {
return err return err
} }
}
defer f.Close() var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, err := w.CreateFormField("payload_json") fw, err := w.CreateFormField("payload_json")
if err != nil { if err != nil {
return err return err
} }
if _, err = fw.Write([]byte(string(json))); err != nil { if _, err = fw.Write([]byte(string(existingJSONBody))); err != nil {
return err return err
} }
...@@ -150,24 +171,8 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error { ...@@ -150,24 +171,8 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error {
w.Close() w.Close()
body = b.Bytes() cmd.Body = string(b.Bytes())
content_type = w.FormDataContentType() cmd.ContentType = w.FormDataContentType()
} else {
body = json
}
cmd := &m.SendWebhookSync{
Url: this.WebhookURL,
Body: string(body),
HttpMethod: "POST",
ContentType: content_type,
}
if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
this.log.Error("Failed to send notification to Discord", "error", err)
return err
}
return nil return nil
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment