Skip to content
Closed
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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,12 @@ To generate a "Service API Key", see [PagerDuty Support: Adding Services](https:

##### [Slack](https://www.slack.com)

The target for a Slack subscription will be the channel name (including the `#`, for example `#channel`). You can optionally suffix the channel name with `!` and that will cause the alerts to include a `@channel` mention (for example `#channel!`).
If you set `SLACK_TOKEN`, the target for a Slack subscription will be the channel name (including the `#`, for example `#channel`). You can optionally suffix the channel name with `!` and that will cause the alerts to include a `@channel` mention (for example `#channel!`). If you set `SLACK_WEBHOOK_URL`, you don't need to suffix the channel, you can simply use `#channel` or `@channel`.

* `SLACK_TOKEN` - The Slack api auth token. Default: ``
Slack notifications can be sent via [Incoming Webhooks](https://api.slack.com/incoming-webhooks) (preferred) or the [Slack Web API](https://api.slack.com/web).

* `SLACK_TOKEN` - The Slack web api auth token. Default: ``
* `SLACK_WEBHOOK_URL` - The Slack webhook URL. If specified, `SLACK_TOKEN` will be ignored. Default: ``
* `SLACK_USERNAME` - The username that messages will be sent to slack. Default: `Seyren`
* `SLACK_ICON_URL` - The user icon URL. Default: ``
* `SLACK_EMOJIS` - Mapping between state and emojis unicode. Default: ``
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,35 @@
*/
package com.seyren.core.service.notification;

import static com.google.common.collect.Iterables.*;
import static com.google.common.collect.Iterables.transform;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
Expand Down Expand Up @@ -65,36 +73,47 @@ protected SlackNotificationService(SeyrenConfig seyrenConfig, String baseUrl) {
}

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException {
String token = seyrenConfig.getSlackToken();
String channel = subscription.getTarget();
String username = seyrenConfig.getSlackUsername();
String iconUrl = seyrenConfig.getSlackIconUrl();

List<String> emojis = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis())
);
public boolean canHandle(SubscriptionType subscriptionType) {
return subscriptionType == SubscriptionType.SLACK;
}

String url = String.format("%s/api/chat.postMessage", baseUrl);
@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException {
String token = seyrenConfig.getSlackToken();
String webhookUrl = seyrenConfig.getSlackWebhook();

String url;
HttpEntity entity;

if (!webhookUrl.isEmpty()) {
LOGGER.debug("Publishing notification using configured Webhook");
url = webhookUrl;
try {
entity = createJsonEntity(check, subscription, alerts);
} catch (JsonProcessingException e) {
throw new NotificationFailedException("Failed to serialize message alert.", e);
}
} else if (!token.isEmpty()){
LOGGER.debug("Publishing notification using slack web API");
url = String.format("%s/api/chat.postMessage", baseUrl);
try {
entity = createFormEntity(check, subscription, alerts);
} catch (UnsupportedEncodingException e) {
throw new NotificationFailedException("Failed to serialize alert.", e);
}
} else {
LOGGER.warn("No SLACK_WEBHOOK_URL or SLACK_TOKEN set. Cannot notify slack.");
return;
}

HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
HttpPost post = new HttpPost(url);
post.addHeader("accept", "application/json");

List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("token", token));
parameters.add(new BasicNameValuePair("channel", StringUtils.removeEnd(channel, "!")));
parameters.add(new BasicNameValuePair("text", formatContent(emojis, check, subscription, alerts)));
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("icon_url", iconUrl));


try {
post.setEntity(new UrlEncodedFormEntity(parameters));
if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
}
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(), new BasicResponseHandler().handleResponse(response));
}
} catch (Exception e) {
Expand All @@ -103,36 +122,51 @@ public void sendNotification(Check check, Subscription subscription, List<Alert>
post.releaseConnection();
HttpClientUtils.closeQuietly(client);
}

}

@Override
public boolean canHandle(SubscriptionType subscriptionType) {
return subscriptionType == SubscriptionType.SLACK;

private HttpEntity createJsonEntity(Check check, Subscription subscription, List<Alert> alerts) throws JsonProcessingException {
Map<String,String> payload = new HashMap<String, String>();
payload.put("channel", subscription.getTarget());
payload.put("username", seyrenConfig.getSlackUsername());
payload.put("text", formatForWebhook(check, subscription, alerts));
payload.put("icon_url", seyrenConfig.getSlackIconUrl());

String message = new ObjectMapper().writeValueAsString(payload);

if (LOGGER.isDebugEnabled()) {
LOGGER.info("> message: {}", message);
}

return new StringEntity(message, ContentType.APPLICATION_JSON);
}

private String formatContent(List<String> emojis, Check check, Subscription subscription, List<Alert> alerts) {
String url = String.format("%s/#/checks/%s", seyrenConfig.getBaseUrl(), check.getId());
String alertsString = Joiner.on("\n").join(transform(alerts, new Function<Alert, String>() {
@Override
public String apply(Alert input) {
return String.format("%s = %s (%s to %s)", input.getTarget(), input.getValue().toString(), input.getFromType(), input.getToType());
}
}));
private HttpEntity createFormEntity(Check check, Subscription subscription, List<Alert> alerts) throws UnsupportedEncodingException {
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("token", seyrenConfig.getSlackToken()));
parameters.add(new BasicNameValuePair("channel", StringUtils.removeEnd(subscription.getTarget(), "!")));
parameters.add(new BasicNameValuePair("text", formatForWebApi(check, subscription, alerts)));
parameters.add(new BasicNameValuePair("username", seyrenConfig.getSlackUsername()));
parameters.add(new BasicNameValuePair("icon_url", seyrenConfig.getSlackIconUrl()));

if (LOGGER.isDebugEnabled()) {
LOGGER.info("> parameters: {}", parameters);
}

return new UrlEncodedFormEntity(parameters);
}

private String formatForWebApi(Check check, Subscription subscription, List<Alert> alerts) {
String url = formatCheckUrl(check);
String alertsString = formatAlert(alerts);

String channel = subscription.getTarget().contains("!") ? "<!channel>" : "";

String description;
if (StringUtils.isNotBlank(check.getDescription())) {
description = String.format("\n> %s", check.getDescription());
} else {
description = "";
}
String description = formatDescription(check);

final String state = check.getState().toString();

return String.format("%s*%s* %s [%s]%s\n```\n%s\n```\n#%s %s",
Iterables.get(emojis, check.getState().ordinal(), ""),
Iterables.get(extractEmojis(), check.getState().ordinal(), ""),
state,
check.getName(),
url,
Expand All @@ -142,4 +176,54 @@ public String apply(Alert input) {
channel
);
}

private String formatForWebhook(Check check, Subscription subscription, List<Alert> alerts) {
String url = formatCheckUrl(check);
String alertsString = formatAlert(alerts);

String description = formatDescription(check);

final String state = check.getState().toString();

return String.format("%s *%s* %s (<%s|Open>)%s\n```\n%s\n```",
Iterables.get(extractEmojis(), check.getState().ordinal(), ""),
state,
check.getName(),
url,
description,
alertsString
);
}

private List<String> extractEmojis() {
List<String> emojis = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis())
);
return emojis;
}

private String formatCheckUrl(Check check) {
String url = String.format("%s/#/checks/%s", seyrenConfig.getBaseUrl(), check.getId());
return url;
}

private String formatAlert(List<Alert> alerts) {
String alertsString = Joiner.on("\n").join(transform(alerts, new Function<Alert, String>() {
@Override
public String apply(Alert input) {
return String.format("%s = %s (%s to %s)", input.getTarget(), input.getValue().toString(), input.getFromType(), input.getToType());
}
}));
return alertsString;
}

private String formatDescription(Check check) {
String description;
if (StringUtils.isNotBlank(check.getDescription())) {
description = String.format("\n> %s", check.getDescription());
} else {
description = "";
}
return description;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public class SeyrenConfig {
private final String ircCatHost;
private final String ircCatPort;
private final String slackToken;
private final String slackWebhook;
private final String slackUsername;
private final String slackIconUrl;
private final String slackEmojis;
Expand Down Expand Up @@ -146,6 +147,7 @@ public SeyrenConfig() {

// Slack
this.slackToken = configOrDefault("SLACK_TOKEN", "");
this.slackWebhook = configOrDefault("SLACK_WEBHOOK_URL", "");
this.slackUsername = configOrDefault("SLACK_USERNAME", "Seyren");
this.slackIconUrl = configOrDefault("SLACK_ICON_URL", "");
this.slackEmojis = configOrDefault("SLACK_EMOJIS", "");
Expand Down Expand Up @@ -396,6 +398,11 @@ public String getSlackToken() {
return slackToken;
}

@JsonIgnore
public String getSlackWebhook() {
return slackWebhook;
}

@JsonIgnore
public String getSlackUsername() {
return slackUsername;
Expand Down
Loading