Skip to content
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

Add ability to send notifications to slack #531

Merged
merged 3 commits into from
Jul 27, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,4 @@ genrule(
# gazelle:exclude pkg/model/piped_stats.pb.validate.go
# gazelle:exclude pkg/model/project.pb.validate.go
# gazelle:exclude pkg/model/role.pb.validate.go
# gazelle:exclude pkg/app/piped/notifier/templates.embed.go
2 changes: 1 addition & 1 deletion hack/expose-generated-go.sh
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ for label in $(bazelisk query 'kind(go_embed_data, //...)'); do
[[ -d "${package}" ]] || continue

# Compute the path where Bazel puts the files.
out_path="bazel-bin/${package}/${OS}_${ARCH}_stripped"
out_path="bazel-bin/${package}"

old_links=${package}/${target}.go
generated_files=${out_path}/${target}.go
Expand Down
5 changes: 0 additions & 5 deletions pkg/app/piped/cmd/piped/piped.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,11 @@ func (p *piped) run(ctx context.Context, t cli.Telemetry) (runErr error) {
},
})
defer func() {
var errMsg string
if runErr != nil {
errMsg = runErr.Error()
}
notifier.Notify(model.Event{
Type: model.EventType_EVENT_PIPED_STOPPED,
Metadata: &model.EventPipedStopped{
Id: cfg.PipedID,
Version: version.Get().Version,
Error: errMsg,
},
})
}()
Expand Down
16 changes: 8 additions & 8 deletions pkg/app/piped/notifier/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ func newMatcher(cfg config.NotificationRoute) *matcher {
}
}

type appIDMetadata interface {
AppID() string
type appNameMetadata interface {
AppName() string
}

type envIDMetadata interface {
Expand All @@ -59,11 +59,11 @@ func (m *matcher) Match(event model.Event) bool {
return false
}

var appID string
if md, ok := event.Metadata.(appIDMetadata); ok {
appID = md.AppID()
var appName string
if md, ok := event.Metadata.(appNameMetadata); ok {
appName = md.AppName()
}
if _, ok := m.ignoreApps[appID]; ok && appID != "" {
if _, ok := m.ignoreApps[appName]; ok && appName != "" {
return false
}

Expand All @@ -86,8 +86,8 @@ func (m *matcher) Match(event model.Event) bool {
return false
}
}
if len(m.apps) > 0 && appID != "" {
if _, ok := m.apps[appID]; !ok {
if len(m.apps) > 0 && appName != "" {
if _, ok := m.apps[appName]; !ok {
return false
}
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/app/piped/notifier/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,23 @@ func TestMatch(t *testing.T) {
Type: model.EventType_EVENT_DEPLOYMENT_TRIGGERED,
Metadata: &model.EventDeploymentTriggered{
Deployment: &model.Deployment{
ApplicationId: "canary",
ApplicationName: "canary",
},
},
}: true,
{
Type: model.EventType_EVENT_DEPLOYMENT_PLANNED,
Metadata: &model.EventDeploymentTriggered{
Deployment: &model.Deployment{
ApplicationId: "bluegreen",
ApplicationName: "bluegreen",
},
},
}: false,
{
Type: model.EventType_EVENT_DEPLOYMENT_SUCCEEDED,
Metadata: &model.EventDeploymentTriggered{
Deployment: &model.Deployment{
ApplicationId: "not-specified",
ApplicationName: "not-specified",
},
},
}: false,
Expand Down
2 changes: 1 addition & 1 deletion pkg/app/piped/notifier/notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func NewNotifier(cfg *config.PipedSpec, logger *zap.Logger) (*Notifier, error) {
var sd sender
switch {
case receiver.Slack != nil:
sd = newSlackSender(receiver.Name, *receiver.Slack, logger)
sd = newSlackSender(receiver.Name, *receiver.Slack, cfg.WebURL, logger)
case receiver.Webhook != nil:
sd = newWebhookSender(receiver.Name, *receiver.Webhook, logger)
default:
Expand Down
218 changes: 212 additions & 6 deletions pkg/app/piped/notifier/slack.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,237 @@
package notifier

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"

"go.uber.org/zap"

"github.com/pipe-cd/pipe/pkg/config"
"github.com/pipe-cd/pipe/pkg/model"
)

const (
slackUsername = "PipeCD"
slackInfoColor = "#212121"
slackSuccessColor = "#2E7D32"
slackErrorColor = "#AF3F52"
slackWarnColor = "#FFB74D"
)

type slack struct {
name string
config config.NotificationReceiverSlack
logger *zap.Logger
name string
config config.NotificationReceiverSlack
webURL string
httpClient *http.Client
eventCh chan model.Event
gracePeriod time.Duration
logger *zap.Logger
}

func newSlackSender(name string, cfg config.NotificationReceiverSlack, logger *zap.Logger) *slack {
func newSlackSender(name string, cfg config.NotificationReceiverSlack, webURL string, logger *zap.Logger) *slack {
return &slack{
name: name,
config: cfg,
logger: logger.Named("slack"),
webURL: strings.TrimRight(webURL, "/"),
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
eventCh: make(chan model.Event, 100),
gracePeriod: 10 * time.Second,
logger: logger.Named("slack"),
}
}

func (s *slack) Run(ctx context.Context) error {
return nil
send := func(ctx context.Context, event model.Event) {
msg, ok := buildSlackMessage(event, s.webURL)
if !ok {
s.logger.Info(fmt.Sprintf("ignore event %s", event.Type.String()))
return
}
if err := s.sendMessage(ctx, msg); err != nil {
s.logger.Error(fmt.Sprintf("unable to send notification to slack: %v", err))
}
}

for {
select {
case event := <-s.eventCh:
send(ctx, event)
case <-ctx.Done():
// TODO: Send all remaining events before exiting.
return nil
}
}
}

func (s *slack) Notify(event model.Event) {
s.eventCh <- event
}

func buildSlackMessage(event model.Event, webURL string) (slackMessage, bool) {
var (
title, link, text string
color = slackInfoColor
timestamp = time.Now().Unix()
fields []slackField
)

generateDeploymentEventData := func(d *model.Deployment) {
link = webURL + "/deployments/" + d.Id
// TODO: Use environment name instead of id.
fields = []slackField{
{"Env", truncateText(d.EnvId, 8), true},
{"Application", makeSlackLink(d.ApplicationName, webURL+"/applications/"+d.ApplicationId), true},
{"Kind", strings.ToLower(d.Kind.String()), true},
{"Deployment", makeSlackLink(truncateText(d.Id, 8), link), true},
{"Triggered By", d.TriggeredBy(), true},
{"Started At", makeSlackDate(d.CreatedAt), true},
}
}
generatePipedEventData := func(id, version string) {
link = webURL + "/settings/piped"
fields = []slackField{
{"Id", id, true},
{"Version", version, true},
}
}

switch event.Type {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just in case, let me confirm that you didn't include intentionally some EventTypes such as EventType_EVENT_APPLICATION_SYNCED etc...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Let me add a TODO for them in the next PR.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, you said adding in the next PR.

case model.EventType_EVENT_DEPLOYMENT_TRIGGERED:
md := event.Metadata.(*model.EventDeploymentTriggered)
title = fmt.Sprintf("Triggered a new deployment for %q", md.Deployment.ApplicationName)
generateDeploymentEventData(md.Deployment)
break
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are these break statements for?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol. Removed them.


case model.EventType_EVENT_DEPLOYMENT_PLANNED:
md := event.Metadata.(*model.EventDeploymentPlanned)
title = fmt.Sprintf("Deployment for %q was planned", md.Deployment.ApplicationName)
text = md.Summary
generateDeploymentEventData(md.Deployment)
break

case model.EventType_EVENT_DEPLOYMENT_SUCCEEDED:
md := event.Metadata.(*model.EventDeploymentSucceeded)
title = fmt.Sprintf("Deployment for %q was completed successfully", md.Deployment.ApplicationName)
color = slackSuccessColor
generateDeploymentEventData(md.Deployment)
break

case model.EventType_EVENT_DEPLOYMENT_FAILED:
md := event.Metadata.(*model.EventDeploymentFailed)
title = fmt.Sprintf("Deployment for %q was failed", md.Deployment.ApplicationName)
text = md.Reason
color = slackErrorColor
generateDeploymentEventData(md.Deployment)
break

case model.EventType_EVENT_DEPLOYMENT_CANCELLED:
md := event.Metadata.(*model.EventDeploymentCancelled)
title = fmt.Sprintf("Deployment for %q was cancelled", md.Deployment.ApplicationName)
text = fmt.Sprintf("Cancelled by %s", md.Commander)
color = slackWarnColor
generateDeploymentEventData(md.Deployment)
break

case model.EventType_EVENT_PIPED_STARTED:
md := event.Metadata.(*model.EventPipedStarted)
title = "A piped has been started"
generatePipedEventData(md.Id, md.Version)
break

case model.EventType_EVENT_PIPED_STOPPED:
md := event.Metadata.(*model.EventPipedStarted)
title = "A piped has been stopped"
generatePipedEventData(md.Id, md.Version)
break

default:
return slackMessage{}, false
}

return makeSlackMessage(title, link, text, color, timestamp, fields...), true
}

type slackMessage struct {
Username string `json:"username"`
Attachments []slackAttachment `json:"attachments,omitempty"`
}

type slackAttachment struct {
Title string `json:"title"`
TitleLink string `json:"title_link"`
Text string `json:"text"`
Fields []slackField `json:"fields"`
Color string `json:"color,omitempty"`
Markdown []string `json:"mrkdwn_in,omitempty"`
Timestamp int64 `json:"ts,omitempty"`
}

type slackField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}

func makeSlackLink(title, url string) string {
return fmt.Sprintf("<%s|%s>", url, title)
}

func makeSlackDate(unix int64) string {
return fmt.Sprintf("<!date^%d^{date_num} {time_secs}|date>", unix)
}

func truncateText(text string, max int) string {
if len(text) <= max {
return text
}
return text[:max] + "..."
}

func makeSlackMessage(title, titleLink, text, color string, timestamp int64, fields ...slackField) slackMessage {
return slackMessage{
Username: slackUsername,
Attachments: []slackAttachment{slackAttachment{
Title: title,
TitleLink: titleLink,
Text: text,
Fields: fields,
Color: color,
Markdown: []string{"text"},
Timestamp: timestamp,
}},
}
}

func (s *slack) sendMessage(ctx context.Context, msg slackMessage) error {
nghialv marked this conversation as resolved.
Show resolved Hide resolved
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(msg); err != nil {
return err
}

req, err := http.NewRequest("POST", s.config.HookURL, buf)
if err != nil {
return err
}

resp, err := s.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1024*1024))
return fmt.Errorf("%s from Slack: %s", resp.Status, strings.TrimSpace(string(body)))
}

return nil
}
1 change: 1 addition & 0 deletions pkg/config/piped.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type PipedSpec struct {
PipedID string
// The path to the key generated for this piped.
PipedKeyFile string
WebURL string `json:"webURL"`
// How often to check whether an application should be synced.
// Default is 1m.
SyncInterval Duration `json:"syncInterval"`
Expand Down
7 changes: 7 additions & 0 deletions pkg/model/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ func (d *Deployment) CommitHash() string {
return d.Trigger.Commit.Hash
}

func (d *Deployment) TriggeredBy() string {
if d.Trigger.Commander != "" {
return d.Trigger.Commander
}
return d.Trigger.Commit.Author
}

// Clone returns a deep copy of the deployment.
func (d *Deployment) Clone() *Deployment {
msg := proto.Clone(d)
Expand Down
Loading