Debian Codegraph @

Nagstamon/servers/Sensu.py

raw symbols SCIP
1 # adapted from the Zenoss.py code
2
3 # Copyright (C) 2017 Vyron Tsingaras <[email protected]> interworks.cloud
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
18
19 from datetime import timezone, datetime
20 import sys
21 import traceback
22 from requests.structures import CaseInsensitiveDict
23
24 from Nagstamon.config import conf
25 from Nagstamon.objects import (GenericHost, GenericService, Result)
26 from Nagstamon.servers.Generic import GenericServer
27 from Nagstamon.thirdparty.sensu_api import SensuAPI, SensuAPIException
28 from Nagstamon.helpers import human_readable_duration_from_timestamp, webbrowser_open
29
30
31 class SensuServer(GenericServer):
32 TYPE = 'Sensu'
33 SEVERITY_CODE_TEXT_MAP = dict()
34 SEVERITY_STATUS_TEXT_MAP = CaseInsensitiveDict()
35
36 MENU_ACTIONS = ['Monitor', 'Recheck', 'Acknowledge', 'Submit check result', 'Downtime']
37
38 sensu_api = None
39 authentication = 'basic'
40 api_url = ''
41 uchiwa_url = ''
42 uchiwa_datacenter = ''
43 username = ''
44 password = ''
45
46 def __init__(self, **kwds):
47 GenericServer.__init__(self, **kwds)
48
49 # Prepare all urls needed by nagstamon
50 self.urls = {}
51 self.statemap = {}
52
53 self.api_url = conf.servers[self.get_name()].monitor_cgi_url
54 self.uchiwa_url = conf.servers[self.get_name()].monitor_url
55 self.uchiwa_datacenter = conf.servers[self.get_name()].monitor_site
56 self.username = conf.servers[self.get_name()].username
57 self.password = conf.servers[self.get_name()].password
58 self.ignore_cert = conf.servers[self.get_name()].ignore_cert
59 self.custom_cert_use = conf.servers[self.get_name()].custom_cert_use
60 self.custom_cert_ca_file = conf.servers[self.get_name()].custom_cert_ca_file
61
62 self.BROWSER_URLS = {
63 'monitor': '$MONITOR$',
64 'hosts': '$MONITOR$/#/clients',
65 'services': '$MONITOR$/#/checks',
66 'history': '$MONITOR$/#/clients'
67 }
68
69 self.SEVERITY_CODE_TEXT_MAP = {
70 0: 'OK',
71 1: 'WARNING',
72 2: 'CRITICAL',
73 3: 'UNKNOWN'
74 }
75 # SEVERITY_STATUS_TEXT_MAP is a Case-Insensitive dict
76 self.SEVERITY_STATUS_TEXT_MAP['OK'] = 0
77 self.SEVERITY_STATUS_TEXT_MAP['WARNING'] = 1
78 self.SEVERITY_STATUS_TEXT_MAP['CRITICAL'] = 2
79 self.SEVERITY_STATUS_TEXT_MAP['UNKNOWN'] = 3
80
81 def init_http(self):
82 """
83 things to do if HTTP is not initialized
84 """
85 GenericServer.init_http(self)
86
87 if self.custom_cert_use:
88 verify = self.custom_cert_ca_file
89 else:
90 verify = not self.ignore_cert
91
92 try:
93 self.sensu_api = SensuAPI(
94 self.api_url,
95 username=self.username,
96 password=self.password,
97 verify=verify
98 )
99 except SensuAPIException:
100 self.error(sys.exc_info())
101
102 def _insert_service_to_hosts(self, service: GenericService):
103 service_host = service.get_host_name()
104 if service_host not in self.new_hosts:
105 self.new_hosts[service_host] = GenericHost()
106 self.new_hosts[service_host].name = service_host
107 self.new_hosts[service_host].site = service.site
108
109 self.new_hosts[service_host].services[service.name] = service
110
111 @staticmethod
112 def _aslocaltimestr(utc_dt):
113 local_dt = utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
114 return local_dt.strftime('%Y-%m-%d %H:%M:%S')
115
116 def _get_status(self):
117 self.new_hosts = dict()
118
119 try:
120 events = self._get_all_events()
121 for event in events:
122 event_check = event['check']
123 event_client = event['client']
124
125 new_service = GenericService()
126 new_service.event_id = event['id']
127 new_service.host = event_client['name']
128 new_service.name = event_check['name']
129 # Uchiwa needs the 'dc' for re_check; Sensu does not
130 if 'dc' in event:
131 new_service.site = event['dc']
132 else:
133 new_service.site = ''
134 new_service.status = ''
135 try:
136 new_service.status = self.SEVERITY_CODE_TEXT_MAP[event_check['status']]
137 except KeyError:
138 new_service.status = 'UNKNOWN'
139 last_check_time = datetime.utcfromtimestamp(int(event['timestamp']))
140 new_service.last_check = self._aslocaltimestr(last_check_time)
141 new_service.duration = human_readable_duration_from_timestamp(int(event['last_state_change']))
142 new_service.status_information = event_check['output']
143 # needs a / with a number on either side to work
144 new_service.attempt = str(event['occurrences']) + '/1'
145 new_service.passiveonly = False
146 new_service.notifications_disabled = event['silenced']
147 new_service.flapping = False
148 new_service.acknowledged = event['silenced']
149 new_service.scheduled_downtime = False
150
151 self._insert_service_to_hosts(new_service)
152 except:
153 self.isChecking = False
154 result, error = self.error(sys.exc_info())
155 print(traceback.format_exc())
156 return Result(result=result, error=error)
157
158 return Result(error="")
159
160 def get_username(self):
161 return str(self.username)
162
163 def get_password(self):
164 return str(self.password)
165
166 def set_acknowledge(self, info_dict):
167 subscription = self._format_client_subscription(info_dict['host'])
168 try:
169 silenece_args = {
170 'check': info_dict['service'],
171 'subscription': subscription,
172 'reason': info_dict['comment'],
173 'creator': info_dict['author'],
174 'expire_on_resolve': True
175 }
176 self.sensu_api.post_silence_request(silenece_args)
177 except SensuAPIException as e:
178 pass
179
180 @staticmethod
181 def _format_client_subscription(client: str):
182 return 'client:' + client
183
184 def _acknowledge_client_check(self, client: str, check: str, comment: str = None, author: str = None):
185 subscription = self._format_client_subscription(client)
186 try:
187 silenece_args = {
188 'check': check,
189 'subscription': subscription,
190 'reason': comment,
191 'creator': author,
192 'expire_on_resolve': True
193 }
194 self.sensu_api.post_silence_request(silenece_args)
195 except SensuAPIException as e:
196 pass
197
198 def _get_all_events(self):
199 events = self.sensu_api.get_events()
200 return events
201
202 def _get_event_duration_string(self, start_seconds: int, end_seconds: int):
203 sec = end_seconds - start_seconds
204
205 days, rem = divmod(sec, 60 * 60 * 24)
206 hours, rem = divmod(rem, 60 * 60)
207 mins, sec = divmod(rem, 60)
208
209 if days == 0 and hours == 0 and mins == 0 and sec == 0:
210 return None
211 return '%sd %sh %sm %ss' % (days, hours, mins, sec)
212
213 def set_recheck(self, info_dict):
214 if info_dict['service'] == 'keepalive':
215 if conf.debug_mode:
216 self.debug(server=self.name, debug='Keepalive results must come from the client running on host {0}, unable to recheck'.format(info_dict['host']))
217 else:
218 standalone = self.sensu_api.get_event(info_dict['host'], info_dict['service'])['check']['standalone']
219 if standalone:
220 if conf.debug_mode:
221 self.debug(server=self.name, debug='Service {0} on host {1} is a standalone service, will not recheck'.format(info_dict['service'], info_dict['host']))
222 else:
223 self.sensu_api.post_check_request(
224 info_dict['service'],
225 self._format_client_subscription(info_dict['host']),
226 self.hosts[info_dict['host']].site
227 )
228
229 def set_downtime(self, info_dict):
230 subscription = self._format_client_subscription(info_dict['host'])
231
232 silence_args = {
233 'check': info_dict['service'],
234 'subscription': subscription,
235 'reason': info_dict['comment'],
236 'creator': info_dict['author'],
237 'expire': int(info_dict['hours']) * 3600 + int(info_dict['minutes']) * 60,
238 'expire_on_resolve': False
239 }
240 self.sensu_api.post_silence_request(silence_args)
241
242 def set_submit_check_result(self, info_dict):
243 sensu_status = None
244 try:
245 sensu_status = self.SEVERITY_STATUS_TEXT_MAP[info_dict['state']]
246 except KeyError:
247 sensu_status = 3 # 3 stands for UNKNOWN, anything other than 0,1,2 is UNKNOWN to Sensu
248 self.sensu_api.post_result_data(info_dict['host'], info_dict['service'],
249 info_dict['check_output'], sensu_status)
250
251 def get_start_end(self, host):
252 return 'Not Supported!', 'Not Supported!'
253
254 def open_monitor(self, host, service=''):
255 '''
256 open monitor from tablewidget context menu
257 '''
258 detail_url = self.monitor_url + '/#/client/' + self.uchiwa_datacenter + '/' + host
259 if service != '':
260 detail_url += '?check=' + service
261 webbrowser_open(detail_url)