-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.rb
109 lines (89 loc) · 2.28 KB
/
handler.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
require 'json'
require 'slack-notifier'
require 'faraday'
def webhook(event:, context:)
body = JSON.parse(event["body"])
p body
if body.dig("alert", "state") == "triggered"
conn = faraday_client(url: body["url_base"])
results = get_query_results(url: body["url_base"], id: body.dig("alert", "query_id"))
message = <<~EOF
#{body.dig("alert", "name")}
#{body["url_base"]}/queries/#{body.dig("alert", "query_id")}
EOF
notify(message, parse_slack_attachments(results, color: "danger"))
end
{
statusCode: 200,
body: {
message: 'Go Serverless v1.0! Your function executed successfully!',
input: body
}.to_json
}
end
def notify(text, attachments = [])
p "notify with: #{text}"
res = slack_client.post(
text: text,
attachments: attachments,
)
p "notify response: #{res}"
res
end
def parse_slack_attachments(results = [], color: good)
results.map do |result|
{
color: color,
fields: result.map do |key, value|
{
title: key,
value: value,
short: is_short?(value),
}
end
}
end
end
def is_short?(value)
case value
when Integer
true
else
false
end
end
def slack_client
@notifier ||= Slack::Notifier.new(ENV["SLACK_WEBHOOK_URL"])
end
def get_query_results(url:, id:)
api_key = get_query_api_key(url: url, id: id)
conn = faraday_client(url: url)
response = conn.get do |req|
req.url "/api/queries/#{id}/results.json"
req.headers['Content-Type'] = 'application/json'
req.headers['Authorization'] = "Key #{api_key}"
end
JSON.parse(response.body).dig("query_result", "data", "rows")
end
def get_query_api_key(url:, id:)
get_redash_query(url: url, id: id)["api_key"]
end
def get_redash_query(url:, id:)
conn = faraday_client(url: url)
response = conn.get do |req|
req.url "/api/queries/#{id}"
req.headers['Content-Type'] = 'application/json'
req.headers['Authorization'] = "Key #{ENV["REDASH_API_KEY"]}"
end
JSON.parse(response.body)
end
def faraday_client(url:)
@clients ||= {}
return @clients[url] if @clients.has_key?(url)
conn = Faraday::Connection.new(url: url) do |builder|
builder.use Faraday::Request::UrlEncoded
builder.use Faraday::Response::Logger
end
@clients[url] = conn
conn
end