Skip to content

Dooray receivers #262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions notify/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package notify

import (
"fmt"
"github.com/grafana/alerting/receivers/dooray"

"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/types"
Expand Down Expand Up @@ -76,6 +77,9 @@ func BuildReceiverIntegrations(
for i, cfg := range receiver.DiscordConfigs {
ci(i, cfg.Metadata, discord.New(cfg.Settings, cfg.Metadata, tmpl, nw(cfg.Metadata), img, nl(cfg.Metadata), version))
}
for i, cfg := range receiver.DoorayConfigs {
ci(i, cfg.Metadata, dooray.New(cfg.Settings, cfg.Metadata, tmpl, nw(cfg.Metadata), nl(cfg.Metadata)))
}
for i, cfg := range receiver.EmailConfigs {
mailCli, e := newEmailSender(cfg.Metadata)
if e != nil {
Expand Down
8 changes: 8 additions & 0 deletions notify/receivers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/grafana/alerting/receivers/dooray"
"net/url"
"strings"
"time"
Expand Down Expand Up @@ -207,6 +208,7 @@ type GrafanaReceiverConfig struct {
WebhookConfigs []*NotifierConfig[webhook.Config]
WecomConfigs []*NotifierConfig[wecom.Config]
WebexConfigs []*NotifierConfig[webex.Config]
DoorayConfigs []*NotifierConfig[dooray.Config]
}

// NotifierConfig represents parsed GrafanaIntegrationConfig.
Expand Down Expand Up @@ -426,6 +428,12 @@ func parseNotifier(ctx context.Context, result *GrafanaReceiverConfig, receiver
return err
}
result.WebexConfigs = append(result.WebexConfigs, newNotifierConfig(receiver, cfg))
case "dooray":
cfg, err := dooray.NewConfig(receiver.Settings, decryptFn)
if err != nil {
return err
}
result.DoorayConfigs = append(result.DoorayConfigs, newNotifierConfig(receiver, cfg))
default:
return fmt.Errorf("notifier %s is not supported", receiver.Type)
}
Expand Down
36 changes: 36 additions & 0 deletions receivers/dooray/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package dooray

import (
"encoding/json"
"errors"
"fmt"

"github.com/grafana/alerting/receivers"
"github.com/grafana/alerting/templates"
)

type Config struct {
Url string `json:"url,omitempty" yaml:"url,omitempty"`
Title string `json:"title,omitempty" yaml:"title,omitempty"`
IconURL string `json:"icon_url,omitempty" yaml:"icon_url,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
}

func NewConfig(jsonData json.RawMessage, decryptFn receivers.DecryptFunc) (Config, error) {
var settings Config
err := json.Unmarshal(jsonData, &settings)
if err != nil {
return Config{}, fmt.Errorf("failed to unmarshal settings: %w", err)
}
settings.Url = decryptFn("url", settings.Url)
if settings.Url == "" {
return Config{}, errors.New("could not find url in settings")
}
if settings.Title == "" {
settings.Title = templates.DefaultMessageTitleEmbed
}
if settings.Description == "" {
settings.Description = templates.DefaultMessageEmbed
}
return settings, nil
}
114 changes: 114 additions & 0 deletions receivers/dooray/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package dooray

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"

receiversTesting "github.com/grafana/alerting/receivers/testing"
"github.com/grafana/alerting/templates"
)

func TestNewConfig(t *testing.T) {
cases := []struct {
name string
settings string
secureSettings map[string][]byte
expectedConfig Config
expectedInitError string
}{
{
name: "Error if empty",
settings: "",
expectedInitError: `failed to unmarshal settings`,
},
{
name: "Error if empty JSON object",
settings: `{}`,
expectedInitError: `could not find url in settings`,
},
{
name: "Error if Token is empty",
settings: `{ "url": "" }`,
expectedInitError: `could not find url in settings`,
},
{
name: "Minimal valid configuration",
settings: `{"url": "test"}`,
expectedConfig: Config{
Title: templates.DefaultMessageTitleEmbed,
Description: templates.DefaultMessageEmbed,
Url: "test",
},
},
{
name: "Should override url from secure settings",
settings: `{"url": "test"}`,
secureSettings: map[string][]byte{
"url": []byte("test-url"),
},
expectedConfig: Config{
Title: templates.DefaultMessageTitleEmbed,
Description: templates.DefaultMessageEmbed,
Url: "test-url",
},
},
{
name: "Should set url from secure settings",
settings: `{}`,
secureSettings: map[string][]byte{
"url": []byte("test-url"),
},
expectedConfig: Config{
Title: templates.DefaultMessageTitleEmbed,
Description: templates.DefaultMessageEmbed,
Url: "test-url",
},
},
{
name: "All empty fields = minimal valid configuration",
settings: `{"url": "", "title": "", "description": "" }`,
secureSettings: map[string][]byte{
"url": []byte("test-url"),
},
expectedConfig: Config{
Title: templates.DefaultMessageTitleEmbed,
Description: templates.DefaultMessageEmbed,
Url: "test-url",
},
},
{
name: "Extracts all fields",
settings: FullValidConfigForTesting,
secureSettings: map[string][]byte{},
expectedConfig: Config{
Title: "test-title",
Description: "test-description",
Url: "test",
},
},
{
name: "Extracts all fields + override from secrets",
settings: FullValidConfigForTesting,
secureSettings: receiversTesting.ReadSecretsJSONForTesting(FullValidSecretsForTesting),
expectedConfig: Config{
Title: "test-title",
Description: "test-description",
Url: "test-secret-url",
},
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
actual, err := NewConfig(json.RawMessage(c.settings), receiversTesting.DecryptForTesting(c.secureSettings))

if c.expectedInitError != "" {
require.ErrorContains(t, err, c.expectedInitError)
return
}
require.Equal(t, c.expectedConfig, actual)
})
}
}
115 changes: 115 additions & 0 deletions receivers/dooray/dooray.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package dooray

import (
"context"
"encoding/json"
"fmt"
"github.com/prometheus/alertmanager/types"
"net/url"

"github.com/grafana/alerting/logging"
"github.com/grafana/alerting/receivers"
"github.com/grafana/alerting/templates"
)

// Notifier is responsible for sending
// alert notifications to Dooray.
type Notifier struct {
*receivers.Base
log logging.Logger
ns receivers.WebhookSender
tmpl *templates.Template
settings Config
}

func New(cfg Config, meta receivers.Metadata, template *templates.Template, sender receivers.WebhookSender, logger logging.Logger) *Notifier {
return &Notifier{
Base: receivers.NewBase(meta),
log: logger,
ns: sender,
tmpl: template,
settings: cfg,
}
}

// Dooray WebHook Request structure
type doorayMessage struct {
BotName string `json:"botName"`
BotIconImage string `json:"botIconImage"`
Text string `json:"text"`
Attachments []attachment `json:"attachments,omitempty"`
}

type attachment struct {
Title string `json:"title"`
TitleLink string `json:"titleLink"`
Text string `json:"text"`
Color string `json:"color"`
}

// Notify send a webhook notification to Dooray
func (dr *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
dr.log.Debug("executing Dooray notification", "notification", dr.Name)

title, body, err := dr.buildMessage(ctx, as...)
if err != nil {
return false, fmt.Errorf("failed to build message: %w", err)
}

form := url.Values{}
form.Add("message", body)

req := &doorayMessage{
BotName: title,
BotIconImage: dr.settings.IconURL,
Text: body,
}

var cmd *receivers.SendWebhookSettings

if jsonReq, err := json.Marshal(req); err != nil {
return false, err
} else {
cmd = &receivers.SendWebhookSettings{
URL: dr.settings.Url,
HTTPMethod: "POST",
HTTPHeader: map[string]string{
"Content-Type": "application/json;charset=UTF-8",
},
Body: string(jsonReq),
}
}

if err := dr.ns.SendWebhook(ctx, cmd); err != nil {
dr.log.Error("failed to send notification to Dooray", "error", err, "body", body)
return false, err
}

return true, nil
}

func (dr *Notifier) SendResolved() bool {
return !dr.GetDisableResolveMessage()
}

func (dr *Notifier) buildMessage(ctx context.Context, as ...*types.Alert) (string, string, error) {
ruleURL := receivers.JoinURLPath(dr.tmpl.ExternalURL.String(), "/alerting/list", dr.log)

var tmplErr error
tmpl, _ := templates.TmplText(ctx, dr.tmpl, as, dr.log, &tmplErr)
if tmplErr != nil {
dr.log.Warn("failed to build Dooray message", "error", tmplErr.Error())
}

title := tmpl(dr.settings.Title)
body := fmt.Sprintf(
"%s\n%s\n\n%s",
title,
ruleURL,
tmpl(dr.settings.Description),
)
if tmplErr != nil {
dr.log.Warn("failed to template Dooray message", "error", tmplErr.Error())
}
return title, body, nil
}
Loading