Class: A2A::Monitoring::SlackAlertChannel

Inherits:
Object
  • Object
show all
Defined in:
lib/a2a/monitoring/alerting.rb

Overview

Slack alert channel

Instance Method Summary collapse

Constructor Details

#initialize(webhook_url, channel: nil, username: "A2A Alerts") ⇒ SlackAlertChannel

Initialize Slack channel

Parameters:

  • webhook_url (String)

    Slack webhook URL

  • channel (String, nil) (defaults to: nil)

    Slack channel name

  • username (String) (defaults to: "A2A Alerts")

    Bot username



409
410
411
412
413
# File 'lib/a2a/monitoring/alerting.rb', line 409

def initialize(webhook_url, channel: nil, username: "A2A Alerts")
  @webhook_url = webhook_url
  @channel = channel
  @username = username
end

Instance Method Details

#format_slack_attachment(alert) ⇒ Hash (private)

Format alert as Slack attachment

Parameters:

  • alert (Hash)

    Alert data

Returns:

  • (Hash)

    Slack attachment



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/a2a/monitoring/alerting.rb', line 448

def format_slack_attachment(alert)
  color = case alert[:severity]
          when :critical then "danger"
          when :error then "danger"
          when :warning then "warning"
          else "good"
          end

  color = "good" if alert[:state] == :resolved

  {
    color: color,
    title: "#{alert[:state].to_s.capitalize}: #{alert[:rule_name]}",
    text: alert[:description],
    fields: [
      {
        title: "Metric",
        value: alert[:metric],
        short: true
      },
      {
        title: "Value",
        value: alert[:value].to_s,
        short: true
      },
      {
        title: "Severity",
        value: alert[:severity].to_s.capitalize,
        short: true
      },
      {
        title: "Time",
        value: (alert[:fired_at] || alert[:resolved_at]).strftime("%Y-%m-%d %H:%M:%S UTC"),
        short: true
      }
    ],
    footer: "A2A Monitoring",
    ts: (alert[:fired_at] || alert[:resolved_at]).to_i
  }
end

#send_alert(alert) ⇒ Object

Send alert to Slack

Parameters:

  • alert (Hash)

    Alert data



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/a2a/monitoring/alerting.rb', line 419

def send_alert(alert)
  payload = {
    username: @username,
    channel: @channel,
    attachments: [format_slack_attachment(alert)]
  }.compact

  uri = URI(@webhook_url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.path)
  request["Content-Type"] = "application/json"
  request.body = payload.to_json

  response = http.request(request)

  return if response.is_a?(Net::HTTPSuccess)

  raise "Slack webhook request failed: #{response.code}"
end