-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslackspace.rb
375 lines (322 loc) · 12.2 KB
/
slackspace.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
require "net/http"
require "uri"
require 'yaml'
require 'json'
require 'fog'
module SlackSpace
RACKSPACE_CREDENTIALS = {
:provider => 'Rackspace',
:rackspace_api_key => ENV['RACKSPACE_API_KEY'],
:rackspace_username => ENV['RACKSPACE_USER_NAME'],
:rackspace_region => ENV['RACKSPACE_REGION']
}
SLACK_WEBHOOK = "https://hooks.slack.com/services/"
SLACK_WEBHOOK_KEY = ENV['SLACK_WEBHOOK_KEY']
SLACKSPACE_BASE_URL = ENV['SLACKSPACE_BASE_URL']
module SlackSpaceHelpers
def credentials
@credentials ||= (YAML.load(session['credentials']) rescue nil) || Hash.new
#puts "@CREDENTIALS #{@credentials.inspect}"
@credentials
end
def credentials=(_credentials=nil)
@credentials = (_credentials || {})
end
def pack_credentials
#puts "PACK_CREDENTIALS #{@credentials.inspect}"
session['credentials'] = @credentials.to_yaml
end
# Should result in a valid Slack incoming-webhook URL.
def endpoint(key=params[:key])
"#{SLACK_WEBHOOK}#{key}"
end
# Master call to process webhook.
def run_webhook(_endpoint=endpoint, body)
#puts "RUN_WEBHOOK endpoint #{_endpoint}"
#puts "RUN_WEBHOOK body #{body}"
webhook = JSON.load(body)
payload = build_payload(webhook)
push_webhook(endpoint=_endpoint, payload)
end
# Push formatted json webhook to Slack.
def push_webhook(_endpoint=endpoint, payload)
#puts "PUSH_WEBHOOK endpoint #{_endpoint}"
#puts "PUSH_WEBHOOK payload #{payload}"
uri = URI.parse(_endpoint)
#puts "PUSH_WEBHOOK uri #{uri}"
response = Net::HTTP.post_form(uri, {:payload=>payload.to_json})
# This longer series of steps gives you more control over the connection, but so far it isn't necessary.
# uri = URI.parse(SLACK_URL)
# http = Net::HTTP.new(uri.host, uri.port)
# req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
# req.body = {:text=>body['alarm']['label'].to_s}.to_json
# response = http.request(req)
#puts "PUSH_WEBHOOK response #{response.to_yaml}"
#puts "PUSH_WEBHOOK TO: #{SLACK_URL} RESPONSE: #{response.inspect} : #{response.message} PAYLOAD: #{payload.inspect}"
response
end
# Build Slack incoming-webhook payload.
def build_payload(webhook)
#puts "BUILD_PAYLOAD webhook #{webhook}"
{ :text => "Rackspace Notification",
:attachments => build_attachments(webhook),
:username => "SlackSpace",
:icon_emoji => ":ghost:"
}
end
# Build Slack incoming-webhook attachments.
def build_attachments(webhook)
#puts "BUILD_ATTACHMENTS webhook #{webhook}"
state = webhook['details']['state']
state_color = case state
when 'CRITICAL'; 'danger'
when 'WARNING'; 'warning'
when 'OK'; 'good'
end
target = webhook['details']['target']
timestamp = Time.at(webhook['details']['timestamp'].to_i/1000).to_s
entity_label = webhook['entity']['label']
entity_ip_address =
if (webhook['entity']['ip_addresses'].nil?)
entity_ip_address="not available"
else
entity_ip_address = webhook['entity']['ip_addresses']['default']
end
check_label = webhook['check']['label']
#check_details = webhook['check']['details'].to_yaml
alarm_label = webhook['alarm']['label']
[
{
"fallback" => "Your browser does not support full display of the Rackspace alarm.",
"color" => state_color,
#"pretext" => "Optional text that appears above the attachment block",
#"author_name" => "Bobby Tables",
#"author_link" => "http://flickr.com/bobby/",
#"author_icon" => "http://flickr.com/icons/bobby.jpg",
"title" => state,
#"title_link" => "https://api.slack.com/",
#"text" => JSON.pretty_generate(webhook) #"Optional text that appears within the attachment",
"fields" => [
{
"title" => "Target",
"value" => target,
"short" => true
},
{
"title" => "Timestamp",
"value" => timestamp,
"short" => true
},
{
"title" => "Entity",
"value" => entity_label,
"short" => true
},
{
"title" => "IP",
"value" => entity_ip_address,
"short" => true
},
{
"title" => "Check",
"value" => check_label,
"short" => true
},
{
"title" => "Alarm",
"value" => alarm_label,
"short" => true
}
],
#"image_url" => "http://my-website.com/path/to/image.jpg",
#"thumb_url" => "http://example.com/path/to/thumb.png"
}
]
end
# # Get webhook json payload as ruby object.
# # This isn't really necessary.
# def parse_webhook(body)
# webhook = JSON.load(body)
# end
## These are for working with Rackspace Monitoring API.
def plan_notifications(plan, type)
#@notifications['values'].find{|n| n['id'] == [plan['critical_state']].flatten[0].to_s }['label'] rescue plan['critical_state']
[plan["#{type}_state"]].flatten.collect{|id| @notifications['values'].find{|n| n['id'] == id}}
end
# Get a Fog::Monitoring api object (from fog library).
def rs_fog_monitor_api(auth = (credentials[:rackspace] || RACKSPACE_CREDENTIALS))
@rs_fog_monitor_api ||= Fog::Monitoring.new(auth)
end
# Get a RackspaceMonitoringApi object (from local library).
def rs_monitor_api(auth = (credentials[:rackspace] || RACKSPACE_CREDENTIALS))
@rs_monitor_api ||= RackspaceMonitoringApi.new(auth)
end
end # SlackSpaceHelpers
# Query & Control Rackspace API
# This is a generic abstract API class.
# Subclass this class for Monitoring, Servers, etc APIs.
class RackspaceApi
attr_accessor :credentials, :last_response, :auth_response
def initialize(_credentials)
@credentials = _credentials
self
end
# Generic comprehensive single-method call for Net::HTTP
# Gist this?
def submit_request(url, http_method=:get, data=nil, headers={})
uri = URI.parse(url)
host = uri.host || 'localhost'
port = uri.port || 80
path = uri.path || '/'
connection = Net::HTTP.new(host, port)
connection.use_ssl=true if uri.scheme.to_s == 'https'
@last_response = connection.start do |http|
req = case http_method.to_sym
when :get; Net::HTTP::Get.new(path, headers)
when :post; Net::HTTP::Post.new(path, headers.merge({'Content-Type' =>'application/json'}))
when :put; Net::HTTP::Put.new(path, headers.merge({'Content-Type' =>'application/json'}))
when :delete; Net::HTTP::Delete.new(path, headers)
end
req.body = data
rsp = http.request(req)
#puts rsp.body
#puts rsp.to_hash.inspect
rsp
end
end
# Wrap generic request with auth credentials, and return json.
def request_json(url, http_method=:get, data=nil, headers={})
resp = from_json(submit_request(url, http_method, data, headers.merge({'X-Auth-Token'=>auth_token})).body)
#puts "REQUEST_JSON response #{resp.inspect}"
resp
end
def from_json(txt)
JSON.load(txt)
end
def auth_token
credentials[:auth_token] || authenticate[:auth_token]
end
def tennant_id
credentials[:tennant_id] || authenticate[:tennant_id]
end
# Authenticate Rackspace user and store tennant_id & auth_token.
# TODO: store auth-token in http session, so don't have to keep getting it.
# Note 2016-07-15: might already be storing auth-token in http session.
def authenticate
if credentials[:auth_token] && credentials[:tennant_id]
credentials
else
#puts "RACKSPACE_AUTHENTICATE"
#puts "RACKSPACE_AUTHENTICATE credentials #{credentials.inspect}" # TODO: DISABLE THIS BEFORE PRODUCTION!
resp = submit_request(
'https://identity.api.rackspacecloud.com/v2.0/tokens',
:post,
{auth:{"RAX-KSKEY:apiKeyCredentials" => {username:credentials[:rackspace_username], apiKey:credentials[:rackspace_api_key]}}}.to_json
)
@auth_response = resp
resp = from_json(@auth_response.body)
credentials[:tennant_id] = resp["access"]["token"]["tenant"]["id"]
credentials[:auth_token] = resp["access"]["token"]["id"]
end
credentials
end
## SHELL SCRIPT
#
# request_json () {
# if [ ! -t 0 ]; then
# local data="`cat -`"
# fi
# local url=$1
# local method=${2:-GET}
#
# if [ "$data" ]; then
# curl -s $url \
# -X $method \
# -d "$data" \
# -H "Content-Type: application/json" \
# -H "X-Auth-Token: $AUTH_TOKEN" | python -m json.tool
# else
# curl -s $url \
# -X $method \
# -H "X-Auth-Token: $AUTH_TOKEN" | python -m json.tool
# fi
# }
end # RackspaceApi
# Manange Rackspace Monitoring notifications and notification plans.
# Subclasses RackspaceApi
class RackspaceMonitoringApi < RackspaceApi
# List cloud monitor notifications
def list_notifications
request_json("https://monitoring.api.rackspacecloud.com/v1.0/#{tennant_id}/notifications")
end
#
#
# Show cloud monitor notification (notification-plan-id)
# Params: notification-plan-id
def show_notification(notification_id)
request_json("https://monitoring.api.rackspacecloud.com/v1.0/#{tennant_id}/notifications/#{notification_id}")
end
#
#
# Test cloud monitor notification, before creating it.
# TODO: Make this input more generic: just the final URL.
def test_notification(webhook_key=SLACK_WEBHOOK_KEY, base_url=SLACKSPACE_BASE_URL)
#puts "TEST_NOTIFICATION WEBHOOK_KEY #{webhook_key}"
request_json("https://monitoring.api.rackspacecloud.com/v1.0/#{tennant_id}/test-notification", :post, <<-EEOOFF)
{
"type": "webhook",
"details": {
"url": "#{base_url}slack/webhook?key=#{webhook_key}"
}
}
EEOOFF
end
# SHELL SCRIPT
#
# # Create cloud monitor notification for webhook
# rs_create_notification () {
# { request_json "https://monitoring.api.rackspacecloud.com/v1.0/$TENANT_ID/notifications" POST | tee rs_create_notification_response.json; } <<-EEOOFF
# {
# "label": "cerneops.slack.com",
# "type": "webhook",
# "details": {
# "url": "https://hooks.slack.com/services/SLACK/WEBHOOK/KEY"
# }
# }
# EEOOFF
# }
#
# Test existing notification (notification-id)
def test_notifications(notification_id)
request_json("https://monitoring.api.rackspacecloud.com/v1.0/#{tennant_id}/notifications/#{notification_id}/test", :post)
end
# List cloud monitor notification plans
def list_notification_plans
request_json("https://monitoring.api.rackspacecloud.com/v1.0/#{tennant_id}/notification_plans")
end
# Show cloud monitor notification (notification-plan-id)
# Params: notification-plan-id
def show_notification_plan(plan_id)
request_json("https://monitoring.api.rackspacecloud.com/v1.0/#{tennant_id}/notification_plans/#{plan_id}")
end
# SHELL SCRIPT
#
# # Create cloud monitor notification plan (label, notify-id-critical, notify-id-warning, notify-id-ok)
# rs_create_notification_plan () {
# { request_json "https://monitoring.api.rackspacecloud.com/v1.0/$TENANT_ID/notification_plans" POST | tee rs_create_notification_plan_response.json; } <<-EEOOFF
# {
# "label": "$1",
# "critical_state": [
# "$2"
# ],
# "warning_state": [
# "$3"
# ],
# "ok_state": [
# "$4"
# ]
# }
# EEOOFF
# }
end # RackspaceMonitoringApi
end # SlackSpace