瀏覽代碼

Merge pull request #15833 from grafana/15694_fix

fix discord notifier so it doesn't crash when there are no image generated
Torkel Ödegaard 6 年之前
父節點
當前提交
64a7d8cefe
共有 1 個文件被更改,包括 43 次插入38 次删除
  1. 43 38
      pkg/services/alerting/notifiers/discord.go

+ 43 - 38
pkg/services/alerting/notifiers/discord.go

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