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

Import PR 163 #1

Merged
merged 3 commits into from
Dec 4, 2023
Merged
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
11 changes: 5 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "slack-app"
version = "0.2.0"
version = "0.3.0"
authors = ["Fiberplane"]
edition = "2021"
build = "build.rs"
Expand Down Expand Up @@ -34,7 +34,7 @@ fiberplane = { version = "1.0.0-beta.7", features = [
] }
form_urlencoded = "1"
futures = "0.3"
mondrian-charts = { version = "0.2.0" }
mondrian-charts = { version = "0.4.0" }
once_cell = "1.13"
opentelemetry = { version = "0.18", features = ["rt-tokio"] }
opentelemetry-otlp = { version = "0.11" }
Expand All @@ -43,7 +43,7 @@ secrecy = { version = "0.8.0", features = ["serde", "bytes"] }
serde = { version = "1.0.133", features = ["derive"] }
serde_json = "1.0.96"
serde_with = "3.0"
slack-morphism = { version = "1.4.2", features = ["hyper"] }
slack-morphism = { git = "https://github.com/actualwitch/slack-morphism-rust.git", branch = "feature/add-attachments-blocks", features = ["hyper"] }
sqlx = { version = "0.7.1", features = [
"runtime-tokio-rustls",
"sqlite",
Expand Down
1 change: 1 addition & 0 deletions migrations/20230911142200_initial.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ CREATE TABLE IF NOT EXISTS alerts
sloth_service TEXT DEFAULT NULL,
sloth_slo TEXT DEFAULT NULL,
objective_name TEXT DEFAULT NULL,
severity TEXT DEFAULT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
Expand Down
6 changes: 6 additions & 0 deletions src/db/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ pub struct Alert {
/// Optional name of the associated objective
pub objective_name: Option<String>,

/// Optional severity of the alert.
pub severity: Option<String>,

/// Timestamp at which the alert was created.
pub created_at: OffsetDateTime,

Expand Down Expand Up @@ -79,4 +82,7 @@ pub struct NewAlert {

/// Optional name of the associated objective
pub objective_name: Option<String>,

/// Optional severity of the alert.
pub severity: Option<String>,
}
7 changes: 4 additions & 3 deletions src/db/sqlite/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ impl Db {
) -> Result<Alert, DbError> {
let now = OffsetDateTime::now_utc();
let alert = sqlx::query_as(
"INSERT INTO alerts ( text, resolved, fingerprint, notebook_id, chart_filename, slack_channel, slack_ts, sloth_slo, sloth_service, objective_name, created_at, updated_at )
VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12 )
"INSERT INTO alerts ( text, resolved, fingerprint, notebook_id, chart_filename, slack_channel, slack_ts, sloth_slo, sloth_service, objective_name, severity, created_at, updated_at )
VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13 )
RETURNING *",
)
.bind(&new_alert.text)
Expand All @@ -36,6 +36,7 @@ impl Db {
.bind(new_alert.sloth_slo.as_ref())
.bind(new_alert.sloth_service.as_ref())
.bind(new_alert.objective_name.as_ref())
.bind(new_alert.severity.as_ref())
.bind(now)
.bind(now)
.fetch_one(&mut **tx)
Expand Down Expand Up @@ -69,7 +70,7 @@ impl Db {
fingerprint: &str,
) -> Result<Option<Alert>, DbError> {
let alert = sqlx::query_as(
"SELECT id, text, resolved, fingerprint, notebook_id, chart_filename, slack_channel, slack_ts, sloth_slo, sloth_service, objective_name, created_at, updated_at
"SELECT id, text, resolved, fingerprint, notebook_id, chart_filename, slack_channel, slack_ts, sloth_slo, sloth_service, objective_name, severity, created_at, updated_at
FROM alerts
WHERE fingerprint = $1",
)
Expand Down
1 change: 1 addition & 0 deletions src/service/alertmanager/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub async fn receive_alertmanager_webhook(
sloth_slo: get_label(alert, &payload, "sloth_slo").map(str::to_owned),
sloth_service: get_label(alert, &payload, "sloth_service").map(str::to_owned),
objective_name: get_label(alert, &payload, "objective_name").map(str::to_owned),
severity: get_label(alert, &payload, "severity").map(str::to_owned),
};

let db_alert = service.db.alert_create(&mut tx, new_alert).await?;
Expand Down
5 changes: 5 additions & 0 deletions src/service/alertmanager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ impl AlertStatus {
}

fn create_alert_text(alert: &AlertmanagerAlert, payload: &AlertmanagerWebhookPayload) -> String {
// Alerts created from Sloth have a "summary" annotation that we can use
if let Some(summary) = alert.annotations.get("summary") {
return summary.to_owned();
}

let get_label = |key| get_label(alert, payload, key);

let mut text = match get_label("alertname") {
Expand Down
3 changes: 2 additions & 1 deletion src/service/charts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,14 @@ impl ChartService {

let chart_options = ChartOptions {
width: 1180,
height: 800,
height: 400,
area_gradient_shown: false,
axis_lines_shown: true,
grid_columns_shown: true,
grid_rows_shown: true,
grid_stroke_color: GRID_STROKE_COLOR,
grid_stroke_dasharray: Default::default(),
shape_stroke_width: Some(4.0),
get_shape_list_color: &get_shape_list_color,
tick_color: TICK_COLOR,
x_formatter: Some(FormatterKind::Time),
Expand Down
105 changes: 77 additions & 28 deletions src/service/slack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,40 +164,89 @@ fn build_message(
explorer_url: Option<&Url>,
alert: &Alert,
) -> Result<SlackMessageContent, SlackServiceError> {
let text = if alert.resolved {
format!(":white_check_mark: ~{text}~", text = alert.text)
let color = if alert.resolved {
// Green
"#2EC95A".to_owned()
} else {
format!(":rotating_light: {text}", text = alert.text)
// Red
"#F2303C".to_owned()
};

let mut content = SlackMessageContent::new().with_blocks(vec![SlackSectionBlock::new()
.with_fields(vec![SlackBlockMarkDownText::new(text).into()])
.into()]);

if alert.chart_filename.is_some() {
content.blocks.as_mut().unwrap().push(
SlackImageBlock::new(
service_base_url
.join(&format!("/api/chart/{}", alert.id))
.unwrap(),
"alert chart".to_owned(),
)
.into(),
let header_text = if alert.resolved {
":white_check_mark: Alert was resolved".to_owned()
} else {
":rotating_light: Alert is firing".to_owned()
};

let header_block = SlackSectionBlock::new().with_text(SlackBlockText::Plain(
SlackBlockPlainText::new(header_text).with_emoji(true),
));

let severity_text = match alert.severity.as_deref() {
Some("page") => ":pager: Page".to_owned(),
Some("ticket") => ":ticket: Ticket".to_owned(),
Some(severity) => format!(":question: {}", severity),
None => ":question: Unknown".to_owned(),
};

let description_block = SlackSectionBlock::new()
.with_text(SlackBlockMarkDownText::new(alert.text.clone()).into())
.with_fields(vec![
SlackBlockMarkDownText::new(format!("*Severity*\n{}", severity_text)).into(),
SlackBlockMarkDownText::new(format!("*Created*\n{}", alert.created_at)).into(),
]);

let chart_block = if let Some(_chart_filename) = alert.chart_filename.as_ref() {
let section: SlackBlock = SlackImageBlock::new(
service_base_url
.join(&format!("/api/chart/{}", alert.id))
.unwrap(),
format!(
"Chart for slo `{}`",
alert.sloth_slo.as_deref().unwrap_or("unknown")
),
)
.into();
Some(section)
} else {
None
};

let actions_block = if let Some(explorer_alert_url) =
get_explorer_alert_url(explorer_url, prometheus_url, alert)
{
let description = format!(
"Triage `{}` SLO in Explorer",
alert.sloth_slo.as_deref().unwrap_or("unknown")
);
}
let explorer_block: SlackBlock = SlackSectionBlock::new()
.with_text(SlackBlockText::MarkDown(SlackBlockMarkDownText::new(
description,
)))
.with_accessory(
SlackBlockButtonElement::new("open_in_explorer".into(), "Open".into())
.with_url(explorer_alert_url)
.into(),
)
.into();
Some(explorer_block)
} else {
None
};

if let Some(blocks) = content.blocks.as_mut() {
if let Some(explorer_alert_url) =
get_explorer_alert_url(explorer_url, prometheus_url, alert)
{
let buttons = vec![SlackActionBlockElement::Button(
SlackBlockButtonElement::new("open_in_explorer".into(), "Open in Explorer".into())
.with_url(explorer_alert_url),
)];
let blocks_maybe: Vec<Option<SlackBlock>> = vec![
Some(header_block.into()),
Some(description_block.into()),
chart_block,
actions_block,
];
let blocks: Vec<SlackBlock> = blocks_maybe.into_iter().flatten().collect();

blocks.push(SlackBlock::Actions(SlackActionsBlock::new(buttons)))
}
}
let attachment = SlackMessageAttachment::new()
.with_color(color)
.with_blocks(blocks);

let content = SlackMessageContent::new().with_attachments(vec![attachment]);

Ok(content)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@
source: slack-app/src/service/slack/tests.rs
expression: message
---
blocks:
- type: section
fields:
- type: mrkdwn
text: ":white_check_mark: ~High Error Rate for \"api\" [environment=production]~"
- type: image
image_url: "http://localhost:3031/api/chart/1234"
alt_text: alert chart
attachments:
- blocks:
- type: section
text:
type: plain_text
text: ":white_check_mark: Alert was resolved"
emoji: true
- type: section
text:
type: mrkdwn
text: "High Error Rate for \"api\" [environment=production]"
fields:
- type: mrkdwn
text: "*Severity*\n:question: Unknown"
- type: mrkdwn
text: "*Created*\n1970-01-01 0:00:00.0 +00:00:00"
- type: image
image_url: "http://localhost:3031/api/chart/1234"
alt_text: "Chart for slo `unknown`"
color: "#2EC95A"

Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,35 @@
source: slack-app/src/service/slack/tests.rs
expression: message
---
blocks:
- type: section
fields:
- type: mrkdwn
text: ":white_check_mark: ~High Error Rate for \"api\" [environment=production]~"
- type: image
image_url: "http://localhost:3031/api/chart/1234"
alt_text: alert chart
- type: actions
elements:
- type: button
action_id: open_in_explorer
attachments:
- blocks:
- type: section
text:
type: plain_text
text: Open in Explorer
url: "http://explorer.pmmp.dev/?prometheusUrl=http://localhost:9090/prometheus#/slos/api/successRate?from=1969-12-31T18:00:00Z&to=1970-01-01T00:00:00Z"
text: ":white_check_mark: Alert was resolved"
emoji: true
- type: section
text:
type: mrkdwn
text: "High Error Rate for \"api\" [environment=production]"
fields:
- type: mrkdwn
text: "*Severity*\n:question: Unknown"
- type: mrkdwn
text: "*Created*\n1970-01-01 0:00:00.0 +00:00:00"
- type: image
image_url: "http://localhost:3031/api/chart/1234"
alt_text: "Chart for slo `success-rate-99`"
- type: section
text:
type: mrkdwn
text: "Triage `success-rate-99` SLO in Explorer"
accessory:
type: button
action_id: open_in_explorer
text:
type: plain_text
text: Open
url: "http://explorer.pmmp.dev/?prometheusUrl=http://localhost:9090/prometheus#/slos/api/successRate?from=1969-12-31T18:00:00Z&to=1970-01-01T00:00:00Z"
color: "#2EC95A"

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,21 @@
source: slack-app/src/service/slack/tests.rs
expression: message
---
blocks:
- type: section
fields:
- type: mrkdwn
text: ":rotating_light: High Error Rate for \"api\" [environment=production]"
attachments:
- blocks:
- type: section
text:
type: plain_text
text: ":rotating_light: Alert is firing"
emoji: true
- type: section
text:
type: mrkdwn
text: "High Error Rate for \"api\" [environment=production]"
fields:
- type: mrkdwn
text: "*Severity*\n:question: Unknown"
- type: mrkdwn
text: "*Created*\n1970-01-01 0:00:00.0 +00:00:00"
color: "#F2303C"

Loading