|
6 | 6 | # Released under the same terms as Sensu (the MIT license); see LICENSE
|
7 | 7 | # for details.
|
8 | 8 |
|
| 9 | +''' |
| 10 | +This provides a base SensuHandler class that can be used for writing |
| 11 | +python-based Sensu handlers. |
| 12 | +''' |
| 13 | + |
| 14 | +from __future__ import print_function |
| 15 | +import os |
| 16 | +import sys |
| 17 | +import json |
| 18 | +import requests |
| 19 | +try: |
| 20 | + from urlparse import urlparse |
| 21 | +except ImportError: |
| 22 | + from urllib.parse import urlparse |
| 23 | +from sensu_plugin.utils import get_settings |
| 24 | + |
9 | 25 |
|
10 | 26 | class SensuHandler(object):
|
| 27 | + ''' |
| 28 | + Class to be used as a basis for handlers. |
| 29 | + ''' |
11 | 30 | def __init__(self):
|
12 |
| - pass |
| 31 | + # Parse the stdin into a global event object |
| 32 | + stdin = sys.stdin.read() |
| 33 | + self.read_event(stdin) |
| 34 | + |
| 35 | + # Prepare global settings |
| 36 | + self.settings = get_settings() |
| 37 | + self.api_settings = self.get_api_settings() |
| 38 | + |
| 39 | + # Filter (deprecated) and handle |
| 40 | + self.filter() |
| 41 | + self.handle() |
| 42 | + |
| 43 | + def read_event(self, check_result): |
| 44 | + ''' |
| 45 | + Convert the piped check result (json) into a global 'event' dict |
| 46 | + ''' |
| 47 | + try: |
| 48 | + self.event = json.loads(check_result) |
| 49 | + self.event['occurrences'] = self.event.get('occurrences', 1) |
| 50 | + self.event['check'] = self.event.get('check', {}) |
| 51 | + self.event['client'] = self.event.get('client', {}) |
| 52 | + except Exception as exception: # pylint: disable=broad-except |
| 53 | + print('error reading event: ' + exception) |
| 54 | + sys.exit(1) |
13 | 55 |
|
14 | 56 | def handle(self):
|
15 |
| - pass |
| 57 | + ''' |
| 58 | + Method that should be overwritten to provide handler logic. |
| 59 | + ''' |
| 60 | + print('ignoring event -- no handler defined') |
16 | 61 |
|
17 | 62 | def filter(self):
|
18 |
| - pass |
| 63 | + ''' |
| 64 | + Filters exit the proccess if the event should not be handled. |
| 65 | + Filtering events is deprecated and will be removed in a future release. |
| 66 | + ''' |
| 67 | + |
| 68 | + if self.deprecated_filtering_enabled(): |
| 69 | + print('warning: event filtering in sensu-plugin is deprecated,' + |
| 70 | + 'see http://bit.ly/sensu-plugin') |
| 71 | + self.filter_disabled() |
| 72 | + self.filter_silenced() |
| 73 | + self.filter_dependencies() |
| 74 | + |
| 75 | + if self.deprecated_occurrence_filtering(): |
| 76 | + print('warning: occurrence filtering in sensu-plugin is' + |
| 77 | + 'deprecated, see http://bit.ly/sensu-plugin') |
| 78 | + self.filter_repeated() |
| 79 | + |
| 80 | + def deprecated_filtering_enabled(self): |
| 81 | + ''' |
| 82 | + Evaluates whether the event should be processed by any of the |
| 83 | + filter methods in this library. Defaults to true, |
| 84 | + i.e. deprecated filters are run by default. |
| 85 | +
|
| 86 | + returns bool |
| 87 | + ''' |
| 88 | + return self.event['check'].get('enable_deprecated_filtering', False) |
| 89 | + |
| 90 | + def deprecated_occurrence_filtering(self): |
| 91 | + ''' |
| 92 | + Evaluates whether the event should be processed by the |
| 93 | + filter_repeated method. Defaults to true, i.e. filter_repeated |
| 94 | + will filter events by default. |
| 95 | +
|
| 96 | + returns bool |
| 97 | + ''' |
| 98 | + |
| 99 | + return self.event['check'].get( |
| 100 | + 'enable_deprecated_occurrence_filtering', False) |
19 | 101 |
|
20 | 102 | def bail(self, msg):
|
21 |
| - pass |
| 103 | + ''' |
| 104 | + Gracefully terminate with message |
| 105 | + ''' |
| 106 | + client_name = self.event.get('client', 'error:no-client-name') |
| 107 | + check_name = self.event['client'].get('name', 'error:no-check-name') |
| 108 | + print('{}: {}/{}'.format(msg, client_name, check_name)) |
| 109 | + sys.exit(0) |
| 110 | + |
| 111 | + def get_api_settings(self): |
| 112 | + ''' |
| 113 | + Return a hash of API settings derived first from ENV['sensu_api_url'] |
| 114 | + if set, then Sensu config `api` scope if configured, and finally |
| 115 | + falling back to to ipv4 localhost address on default API port. |
| 116 | +
|
| 117 | + return dict |
| 118 | + ''' |
| 119 | + |
| 120 | + sensu_api_url = os.environ.get('sensu_api_url') |
| 121 | + if sensu_api_url: |
| 122 | + uri = urlparse(sensu_api_url) |
| 123 | + self.api_settings = { |
| 124 | + 'host': '{0}//{1}'.format(uri.scheme, uri.hostname), |
| 125 | + 'port': uri.port, |
| 126 | + 'user': uri.username, |
| 127 | + 'password': uri.password |
| 128 | + } |
| 129 | + else: |
| 130 | + self.api_settings = self.settings.get('api', {}) |
| 131 | + self.api_settings['host'] = self.api_settings.get( |
| 132 | + 'host', '127.0.0.1') |
| 133 | + self.api_settings['port'] = self.api_settings.get( |
| 134 | + 'port', 4567) |
| 135 | + |
| 136 | + # API requests |
| 137 | + def api_request(self, method, path): |
| 138 | + ''' |
| 139 | + Query Sensu api for information. |
| 140 | + ''' |
| 141 | + if not hasattr(self, 'api_settings'): |
| 142 | + ValueError('api.json settings not found') |
| 143 | + |
| 144 | + if method.lower() == 'get': |
| 145 | + _request = requests.get |
| 146 | + elif method.lower() == 'post': |
| 147 | + _request = requests.post |
| 148 | + |
| 149 | + domain = self.api_settings['host'] |
| 150 | + uri = 'http://{}:{}{}'.format(domain, self.api_settings['port'], path) |
| 151 | + if self.api_settings['user'] and self.api_settings['password']: |
| 152 | + auth = (self.api_settings['user'], self.api_settings['password']) |
| 153 | + else: |
| 154 | + auth = () |
| 155 | + req = _request(uri, auth=auth) |
| 156 | + return req |
| 157 | + |
| 158 | + def stash_exists(self, path): |
| 159 | + ''' |
| 160 | + Query Sensu API for stash data. |
| 161 | + ''' |
| 162 | + return self.api_request('get', '/stash' + path).status_code == 200 |
| 163 | + |
| 164 | + def event_exists(self, client, check): |
| 165 | + ''' |
| 166 | + Query Sensu API for event. |
| 167 | + ''' |
| 168 | + return self.api_request( |
| 169 | + 'get', |
| 170 | + 'events/{}/{}'.format(client, check) |
| 171 | + ).status_code == 200 |
| 172 | + |
| 173 | + # Filters |
| 174 | + def filter_disabled(self): |
| 175 | + ''' |
| 176 | + Determine whether a check is disabled and shouldn't handle. |
| 177 | + ''' |
| 178 | + if self.event['check']['alert'] is False: |
| 179 | + self.bail('alert disabled') |
| 180 | + |
| 181 | + def filter_silenced(self): |
| 182 | + ''' |
| 183 | + Determine whether a check is silenced and shouldn't handle. |
| 184 | + ''' |
| 185 | + stashes = [ |
| 186 | + ('client', '/silence/{}'.format(self.event['client']['name'])), |
| 187 | + ('check', '/silence/{}/{}'.format( |
| 188 | + self.event['client']['name'], |
| 189 | + self.event['check']['name'])), |
| 190 | + ('check', '/silence/all/{}'.format(self.event['check']['name'])) |
| 191 | + ] |
| 192 | + for scope, path in stashes: |
| 193 | + if self.stash_exists(path): |
| 194 | + self.bail(scope + ' alerts silenced') |
| 195 | + |
| 196 | + def filter_dependencies(self): |
| 197 | + ''' |
| 198 | + Determine whether a check has dependencies. |
| 199 | + ''' |
| 200 | + dependencies = self.event['check'].get('dependencies', None) |
| 201 | + if dependencies is None or not isinstance(dependencies, list): |
| 202 | + return |
| 203 | + for dependency in self.event['check']['dependencies']: |
| 204 | + if not str(dependency): |
| 205 | + continue |
| 206 | + dependency_split = tuple(dependency.split('/')) |
| 207 | + # If there's a dependency on a check from another client, then use |
| 208 | + # that client name, otherwise assume same client. |
| 209 | + if len(dependency_split) == 2: |
| 210 | + client, check = dependency_split |
| 211 | + else: |
| 212 | + client = self.event['client']['name'] |
| 213 | + check = dependency_split[0] |
| 214 | + if self.event_exists(client, check): |
| 215 | + self.bail('check dependency event exists') |
| 216 | + |
| 217 | + def filter_repeated(self): |
| 218 | + ''' |
| 219 | + Determine whether a check is repeating. |
| 220 | + ''' |
| 221 | + defaults = { |
| 222 | + 'occurrences': 1, |
| 223 | + 'interval': 30, |
| 224 | + 'refresh': 1800 |
| 225 | + } |
| 226 | + |
| 227 | + # Override defaults with anything defined in the settings |
| 228 | + if isinstance(self.settings['sensu_plugin'], dict): |
| 229 | + defaults.update(self.settings['sensu_plugin']) |
| 230 | + |
| 231 | + occurrences = int(self.event['check'].get( |
| 232 | + 'occurrences', defaults['occurrences'])) |
| 233 | + interval = int(self.event['check'].get( |
| 234 | + 'interval', defaults['interval'])) |
| 235 | + refresh = int(self.event['check'].get( |
| 236 | + 'refresh', defaults['refresh'])) |
| 237 | + |
| 238 | + if self.event['occurrences'] < occurrences: |
| 239 | + self.bail('not enough occurrences') |
| 240 | + |
| 241 | + if (self.event['occurrences'] > occurrences and |
| 242 | + self.event['action'] == 'create'): |
| 243 | + return |
| 244 | + |
| 245 | + number = int(refresh / interval) |
| 246 | + if (number == 0 or |
| 247 | + (self.event['occurrences'] - occurrences) % number == 0): |
| 248 | + return |
| 249 | + |
| 250 | + self.bail('only handling every ' + str(number) + ' occurrences') |
0 commit comments