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,63 +111,68 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error { ...@@ -111,63 +111,68 @@ 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
w := multipart.NewWriter(&b)
f, err := os.Open(evalContext.ImageOnDiskPath)
if !embeddedImage {
cmd.Body = string(json)
} else {
err := this.embedImage(cmd, evalContext.ImageOnDiskPath, json)
if err != nil { if err != nil {
this.log.Error("Can't open graph file", err) this.log.Error("failed to embed image", "error", err)
return err return err
} }
}
defer f.Close() if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
this.log.Error("Failed to send notification to Discord", "error", err)
fw, err := w.CreateFormField("payload_json") return err
if err != nil { }
return err
}
if _, err = fw.Write([]byte(string(json))); err != nil { return nil
return err }
}
fw, err = w.CreateFormFile("file", "graph.png") func (this *DiscordNotifier) embedImage(cmd *m.SendWebhookSync, imagePath string, existingJSONBody []byte) error {
if err != nil { f, err := os.Open(imagePath)
return err defer f.Close()
if err != nil {
if os.IsNotExist(err) {
cmd.Body = string(existingJSONBody)
return nil
} }
if !os.IsNotExist(err) {
if _, err = io.Copy(fw, f); err != nil {
return err return err
} }
}
w.Close() var b bytes.Buffer
w := multipart.NewWriter(&b)
body = b.Bytes() fw, err := w.CreateFormField("payload_json")
content_type = w.FormDataContentType() if err != nil {
return err
}
} else { if _, err = fw.Write([]byte(string(existingJSONBody))); err != nil {
body = json return err
} }
cmd := &m.SendWebhookSync{ fw, err = w.CreateFormFile("file", "graph.png")
Url: this.WebhookURL, if err != nil {
Body: string(body), return err
HttpMethod: "POST",
ContentType: content_type,
} }
if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil { if _, err = io.Copy(fw, f); err != nil {
this.log.Error("Failed to send notification to Discord", "error", err)
return err return err
} }
w.Close()
cmd.Body = string(b.Bytes())
cmd.ContentType = w.FormDataContentType()
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