Skip to content

Commit 104b972

Browse files
committed
Working on pep8
1 parent 07278c4 commit 104b972

File tree

2 files changed

+94
-77
lines changed

2 files changed

+94
-77
lines changed

sensu_plugin/handler.py

Lines changed: 51 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212
import requests
1313
try:
1414
from urlparse import urlparse
15-
except:
15+
except ImportError:
1616
from urllib.parse import urlparse
1717
from utils import *
1818

19+
1920
class SensuHandler(object):
2021
def __init__(self):
2122
# Parse the stdin into a global event object
@@ -29,7 +30,7 @@ def __init__(self):
2930
# Filter (deprecated) and handle
3031
self.filter()
3132
self.handle()
32-
33+
3334
def read_event(self, check_result):
3435
'''
3536
Convert the piped check result (json) into a global 'event' dict
@@ -52,31 +53,31 @@ def handle(self):
5253
def filter(self):
5354
'''
5455
Filters exit the proccess if the event should not be handled.
55-
5656
Filtering events is deprecated and will be removed in a future release.
5757
'''
5858

5959
if self.deprecated_filtering_enabled():
60-
print('warning: event filtering in sensu-plugin is deprecated, see http://bit.ly/sensu-plugin')
60+
print('warning: event filtering in sensu-plugin is deprecated,' +
61+
'see http://bit.ly/sensu-plugin')
6162
self.filter_disabled()
6263
self.filter_silenced()
6364
self.filter_dependencies()
6465

6566
if self.deprecated_occurrence_filtering_enabled():
66-
print('warning: occurrence filtering in sensu-plugin is deprecated, see http://bit.ly/sensu-plugin')
67+
print('warning: occurrence filtering in sensu-plugin is' +
68+
'deprecated, see http://bit.ly/sensu-plugin')
6769
self.filter_repeated()
6870

6971
def deprecated_filtering_enabled(self):
7072
'''
7173
Evaluates whether the event should be processed by any of the
7274
filter methods in this library. Defaults to true,
7375
i.e. deprecated filters are run by default.
74-
76+
7577
returns bool
7678
'''
7779
return self.event['check'].get('enable_deprecated_filtering', False)
7880

79-
8081
def deprecated_occurrence_filtering_enabled(self):
8182
'''
8283
Evaluates whether the event should be processed by the
@@ -86,7 +87,8 @@ def deprecated_occurrence_filtering_enabled(self):
8687
returns bool
8788
'''
8889

89-
return self.event['check'].get('enable_deprecated_occurrence_filtering', False)
90+
return self.event['check'].get(
91+
'enable_deprecated_occurrence_filtering', False)
9092

9193
def bail(self, msg):
9294
'''
@@ -99,27 +101,29 @@ def bail(self, msg):
99101

100102
def get_api_settings(self):
101103
'''
102-
Return a hash of API settings derived first from ENV['SENSU_API_URL'] if set,
103-
then Sensu config `api` scope if configured, and finally falling back to
104-
to ipv4 localhost address on default API port.
105-
104+
Return a hash of API settings derived first from ENV['SENSU_API_URL']
105+
if set, then Sensu config `api` scope if configured, and finally
106+
falling back to to ipv4 localhost address on default API port.
107+
106108
return dict
107109
'''
108110

109111
SENSU_API_URL = os.environ.get('SENSU_API_URL')
110112
if SENSU_API_URL:
111113
uri = urlparse(SENSU_API_URL)
112114
self.api_settings = {
113-
'host': '{0}//{1}'.format(uri.scheme,uri.hostname),
114-
'port': uri.port,
115-
'user': uri.username,
116-
'password': uri.password
115+
'host': '{0}//{1}'.format(uri.scheme, uri.hostname),
116+
'port': uri.port,
117+
'user': uri.username,
118+
'password': uri.password
117119
}
118120
else:
119-
self.api_settings = self.settings.get('api',{})
120-
self.api_settings['host'] = self.api_settings.get('host', '127.0.0.1')
121-
self.api_settings['port'] = self.api_settings.get('port', 4567)
122-
121+
self.api_settings = self.settings.get('api', {})
122+
self.api_settings['host'] = self.api_settings.get(
123+
'host', '127.0.0.1')
124+
self.api_settings['port'] = self.api_settings.get(
125+
'port', 4567)
126+
123127
# API requests
124128
def api_request(method, path, blk):
125129
if not hasattr(self, 'api_settings'):
@@ -129,7 +133,7 @@ def api_request(method, path, blk):
129133
_request = requests.get
130134
elif method.lower() == 'post':
131135
_request = requests.post
132-
136+
133137
domain = self.api_settings['host']
134138
# TODO: http/https
135139
uri = 'http://{}:{}{}'.format(domain, self.api_settings['port'], path)
@@ -139,33 +143,37 @@ def api_request(method, path, blk):
139143
auth = ()
140144
req = _request(uri, auth=auth)
141145
return req
142-
146+
143147
def stash_exists(self, path):
144148
return self.api_request('get', '/stash' + path).status_code == 200
145149

146150
def event_exists(self, client, check):
147-
return self.api_request('get', '/events/' + client + '/' + check).status_code == 200
151+
return self.api_request('get',
152+
'/events/{}/{}'.format(client, check)
153+
).status_code == 200
148154

149155
# Filters
150156
def filter_disabled(self):
151-
if self.event['check']['alert'] == False:
157+
if self.event['check']['alert'] is False:
152158
bail('alert disabled')
153159

154160
def filter_silenced(self):
155161
stashes = [
156-
('client', '/silence/' + self.event['client']['name']),
157-
('check', '/silence/' + self.event['client']['name'] + '/' + self.event['check']['name']),
158-
('check', '/silence/all/' + self.event['check']['name'])
162+
('client', '/silence/{}'.format(self.event['client']['name'])),
163+
('check', '/silence/{}/{}'.format(
164+
self.event['client']['name'],
165+
self.event['check']['name'])),
166+
('check', '/silence/all/{}'.format(self.event['check']['name']))
159167
]
160168
for scope, path in stashes:
161169
if stash_exists(path):
162170
bail(scope + ' alerts silenced')
163171
# TODO: Timeout for querying Sensu API?
164-
# More appropriate in the api_request method?
172+
# More appropriate in the api_request method?
165173

166174
def filter_dependencies(self):
167175
dependencies = self.event['check'].get('dependencies', None)
168-
if dependencies == None or not isinstance(dependencies, list):
176+
if dependencies is None or not isinstance(dependencies, list):
169177
return
170178
for dependency in self.event['check']['dependencies']:
171179
if len(str(dependency)) == 0:
@@ -174,38 +182,42 @@ def filter_dependencies(self):
174182
# If there's a dependency on a check from another client, then use
175183
# that client name, otherwise assume same client.
176184
if len(dependency_split) == 2:
177-
client,check = dependency_split
185+
client, check = dependency_split
178186
else:
179187
client = self.event['client']['name']
180188
check = dependency_split[0]
181189
if self.event_exists(client, check):
182190
bail('check dependency event exists')
183191

184-
185192
def filter_repeated(self):
186193
defaults = {
187194
'occurrences': 1,
188195
'interval': 30,
189196
'refresh': 1800
190197
}
191198

192-
# Override defaults with anything defined in the settings
199+
# Override defaults with anything defined in the settings
193200
if isinstance(self.settings['sensu_plugin'], dict):
194201
defaults.update(settings['sensu_plugin'])
195202
end
196203

197-
occurrences = int(self.event['check'].get('occurrences', defaults['occurrences']))
198-
interval = int(self.event['check'].get('interval', defaults['interval']))
199-
refresh = int(self.event['check'].get('refresh', defaults['refresh']))
204+
occurrences = int(self.event['check'].get(
205+
'occurrences', defaults['occurrences']))
206+
interval = int(self.event['check'].get(
207+
'interval', defaults['interval']))
208+
refresh = int(self.event['check'].get(
209+
'refresh', defaults['refresh']))
200210

201211
if self.event['occurrences'] < occurrences:
202212
bail('not enough occurrences')
203-
204-
if self.event['occurrences'] > occurrences and self.event['action'] == 'create':
213+
214+
if (self.event['occurrences'] > occurrences and
215+
self.event['action'] == 'create'):
205216
return
206-
217+
207218
number = int(refresh / interval)
208-
if (number == 0) or ((self.event['occurrences'] - occurrences) % number == 0):
219+
if (number == 0 or
220+
(self.event['occurrences'] - occurrences) % number == 0):
209221
return
210222

211223
bail('only handling every ' + str(number) + ' occurrences')

sensu_plugin/utils/__init__.py

Lines changed: 43 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,53 @@
11
import os
22
import json
33

4+
45
def config_files():
5-
SENSU_LOADED_TEMPFILE = os.environ.get('SENSU_LOADED_TEMPFILE')
6-
SENSU_CONFIG_FILES = os.environ.get('SENSU_CONFIG_FILES')
7-
if SENSU_LOADED_TEMPFILE and os.path.isfile(SENSU_LOADED_TEMPLATE):
8-
with open(SENSU_LOADED_TEMPLATE, 'r') as template:
9-
contents = template.read()
10-
return contents.split(':')
11-
elif SENSU_CONFIG_FILES:
12-
return SENSU_CONFIG_FILES.split(':')
13-
else:
14-
files = ['/etc/sensu/config.json']
15-
[files.append('/etc/sensu/conf.d/' + filename) for filename in os.listdir('/etc/sensu/conf.d') if os.path.splitext(filename)[1] == '.json']
16-
return files
6+
SENSU_LOADED_TEMPFILE = os.environ.get('SENSU_LOADED_TEMPFILE')
7+
SENSU_CONFIG_FILES = os.environ.get('SENSU_CONFIG_FILES')
8+
if SENSU_LOADED_TEMPFILE and os.path.isfile(SENSU_LOADED_TEMPLATE):
9+
with open(SENSU_LOADED_TEMPLATE, 'r') as template:
10+
contents = template.read()
11+
return contents.split(':')
12+
elif SENSU_CONFIG_FILES:
13+
return SENSU_CONFIG_FILES.split(':')
14+
else:
15+
files = ['/etc/sensu/config.json']
16+
[files.append('/etc/sensu/conf.d/{}'.format(filename))
17+
for filename in os.listdir('/etc/sensu/conf.d')
18+
if os.path.splitext(filename)[1] == '.json']
19+
return files
20+
1721

1822
def get_settings():
19-
settings = {}
20-
for config_file in config_files():
21-
config_contents = load_config(config_file)
22-
if config_contents != None:
23-
settings = deep_merge(settings, config_contents)
24-
return settings
23+
settings = {}
24+
for config_file in config_files():
25+
config_contents = load_config(config_file)
26+
if config_contents is not None:
27+
settings = deep_merge(settings, config_contents)
28+
return settings
29+
2530

2631
def load_config(filename):
27-
try:
28-
with open(filename, 'r') as config_file:
29-
return json.loads(config_file.read())
30-
except:
31-
{}
32+
try:
33+
with open(filename, 'r') as config_file:
34+
return json.loads(config_file.read())
35+
except FileNotFoundError:
36+
{}
3237

33-
def deep_merge(dict_one, dict_two):
34-
merged = dict_one.copy()
35-
for key,value in dict_two.items():
36-
# value is equivalent to dict_two[key]
37-
if (key in dict_one and
38-
isinstance(dict_one[key], dict) and
39-
isinstance(value, dict)):
40-
merged[key] = deep_merge(dict_one[key], value)
41-
elif (key in dict_one and
42-
isinstance(dict_one[key], list) and
43-
isinstance(value, list)):
44-
merged[key] = list(set(dict_one[key] + value))
45-
else:
46-
merged[key] = value
47-
return merged
4838

39+
def deep_merge(dict_one, dict_two):
40+
merged = dict_one.copy()
41+
for key, value in dict_two.items():
42+
# value is equivalent to dict_two[key]
43+
if (key in dict_one and
44+
isinstance(dict_one[key], dict) and
45+
isinstance(value, dict)):
46+
merged[key] = deep_merge(dict_one[key], value)
47+
elif (key in dict_one and
48+
isinstance(dict_one[key], list) and
49+
isinstance(value, list)):
50+
merged[key] = list(set(dict_one[key] + value))
51+
else:
52+
merged[key] = value
53+
return merged

0 commit comments

Comments
 (0)