-
Notifications
You must be signed in to change notification settings - Fork 156
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
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 { | ||
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What are these There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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...There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍
There was a problem hiding this comment.
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.