blob: cf2f4c62fbd2552359b6bbf0b9a28e38cae3838f [file] [log] [blame]
Michal Kobusaa3accf2019-06-05 12:25:09 +02001import fcntl
2import hashlib
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +01003import logging
Michal Kobusaa3accf2019-06-05 12:25:09 +02004import os
Michal Kobus211ee922019-04-15 17:44:06 +02005import time
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +01006import uuid
Michal Kobusaa3accf2019-06-05 12:25:09 +02007from contextlib import contextmanager
8
9from cachetools import TTLCache
Michal Kobus915f3cf2018-12-10 20:09:41 +010010
Michal Kobusafbf4d02018-11-28 14:18:05 +010011from prometheus_client import Counter, Gauge
12
Michal Kobus915f3cf2018-12-10 20:09:41 +010013from requests import Session
Michal Kobusaa3accf2019-06-05 12:25:09 +020014from requests.exceptions import ConnectionError as RequestsConnectionError
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +010015
16from simple_salesforce import Salesforce
Michal Kobusaa3accf2019-06-05 12:25:09 +020017from simple_salesforce import exceptions as sf_exceptions
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +010018
19
Michal Kobusaa3accf2019-06-05 12:25:09 +020020STATE_MAP = {
21 'OK': '060 Informational',
22 'UP': '060 Informational',
23 'UNKNOWN': '070 Unknown',
24 'WARNING': '080 Warning',
25 'MINOR': '080 Warning',
26 'MAJOR': '090 Critical',
27 'CRITICAL': '090 Critical',
28 'DOWN': '090 Critical',
29 'UNREACHABLE': '090 Critical',
30}
31
32CONFIG_FIELD_MAP = {
33 'auth_url': 'instance_url',
34 'username': 'username',
35 'password': 'password',
36 'organization_id': 'organizationId',
37 'environment_id': 'environment_id',
38 'sandbox_enabled': 'domain',
Michal Kobus2e85ef82021-06-24 18:01:43 +020039 'feed_enabled': 'feed_enabled',
40 'hash_func': 'hash_func',
Michal Kobusaa3accf2019-06-05 12:25:09 +020041}
42
43ALLOWED_HASHING = ('md5', 'sha256')
44SESSION_FILE = '/tmp/session'
Michal Kobus73d33522018-12-10 11:41:13 +010045
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +010046logger = logging.getLogger(__name__)
47
48
Michal Kobusaa3accf2019-06-05 12:25:09 +020049@contextmanager
50def flocked(fd):
51 try:
52 fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
53 yield
54 except IOError:
55 logger.info('Session file locked. Waiting 5 seconds...')
56 time.sleep(5)
57 finally:
58 fcntl.flock(fd, fcntl.LOCK_UN)
59
60
61def sf_auth_retry(method):
62 def wrapper(self, *args, **kwargs):
63 try:
64 return method(self, *args, **kwargs)
65 except sf_exceptions.SalesforceExpiredSession:
66 logger.warning('Salesforce session expired.')
67 self.auth()
68 except RequestsConnectionError:
69 logger.error('Salesforce connection error.')
70 self.auth()
71 return method(self, *args, **kwargs)
72 return wrapper
73
74
75class SfNotifierError(Exception):
76 pass
77
78
79class SalesforceClient(object):
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +010080
81 def __init__(self, config):
Michal Kobusafbf4d02018-11-28 14:18:05 +010082 self.metrics = {
83 'sf_auth_ok': Gauge('sf_auth_ok', 'sf-notifier'),
84 'sf_error_count': Counter('sf_error_count', 'sf-notifier'),
85 'sf_request_count': Counter('sf_request_count', 'sf-notifier')
86 }
Michal Kobusaa3accf2019-06-05 12:25:09 +020087 self._registered_alerts = TTLCache(maxsize=2048, ttl=300)
Michal Kobus2e85ef82021-06-24 18:01:43 +020088
89 self.config = self._validate_config(config)
90 self.hash_func = self._hash_func(self.config.pop('hash_func'))
91 self.feed_enabled = self.config.pop('feed_enabled')
92
93 self.environment = self.config.pop('environment_id')
Michal Kobus211ee922019-04-15 17:44:06 +020094 self.sf = None
95 self.session = Session()
96 self.auth()
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +010097
Michal Kobusaa3accf2019-06-05 12:25:09 +020098 @staticmethod
Michal Kobus2e85ef82021-06-24 18:01:43 +020099 def _hash_func(name):
Michal Kobusaa3accf2019-06-05 12:25:09 +0200100 if name in ALLOWED_HASHING:
101 return getattr(hashlib, name)
Michal Kobus2e85ef82021-06-24 18:01:43 +0200102 msg = ('Invalid hashing function "{}".'
103 'Switching to default "sha256".').format(name)
104 logger.warn(msg)
Michal Kobusaa3accf2019-06-05 12:25:09 +0200105 return hashlib.sha256
106
107 @staticmethod
108 def _validate_config(config):
109 kwargs = {}
110
Michal Kobus2e85ef82021-06-24 18:01:43 +0200111 for param, value in config.items():
112 field = CONFIG_FIELD_MAP.get(param.lower())
113 if field is None:
114 env_var = 'SFDC_{}'.format(param)
115 msg = ('Invalid config: missing "{}" field or "{}" environment'
116 ' variable.').format(field, env_var)
117 logger.error(msg)
118 raise SfNotifierError(msg)
119
120 kwargs[field] = value
Michal Kobusaa3accf2019-06-05 12:25:09 +0200121
122 if field == 'domain':
Michal Kobus2e85ef82021-06-24 18:01:43 +0200123 if value:
Michal Kobusaa3accf2019-06-05 12:25:09 +0200124 kwargs[field] = 'test'
125 else:
126 del kwargs[field]
Michal Kobusaa3accf2019-06-05 12:25:09 +0200127
Michal Kobusaa3accf2019-06-05 12:25:09 +0200128 return kwargs
129
Michal Kobus211ee922019-04-15 17:44:06 +0200130 def _auth(self, config):
Michal Kobus17726ae2018-11-27 12:59:55 +0100131 try:
Michal Kobus211ee922019-04-15 17:44:06 +0200132 config.update({'session': self.session})
133 self.sf = Salesforce(**config)
Michal Kobusaa3accf2019-06-05 12:25:09 +0200134 except sf_exceptions.SalesforceAuthenticationFailed as ex:
Michal Kobusf0046f52019-04-24 12:56:41 +0200135 logger.error('Salesforce authentication failure: {}.'.format(ex))
Michal Kobusafbf4d02018-11-28 14:18:05 +0100136 self.metrics['sf_auth_ok'].set(0)
Michal Kobus211ee922019-04-15 17:44:06 +0200137 return False
138
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100139 logger.info('Salesforce authentication successful.')
Michal Kobusafbf4d02018-11-28 14:18:05 +0100140 self.metrics['sf_auth_ok'].set(1)
Michal Kobus211ee922019-04-15 17:44:06 +0200141 return True
142
Michal Kobusaa3accf2019-06-05 12:25:09 +0200143 def _load_session(self, session_file):
144 lines = session_file.readlines()
145
146 if lines == []:
147 return
148 return lines[0]
149
Michal Kobus211ee922019-04-15 17:44:06 +0200150 def _refresh_ready(self, saved_session):
151 if saved_session is None:
152 logger.info('Current session is None.')
153 return True
154
155 if self.sf is None:
156 return False
157
158 if self.sf.session_id == saved_session:
159 return True
160 return False
161
162 def _reuse_session(self, saved_session):
163 logger.info('Reusing session id from file.')
164 # limit params to avoid login request
165 config = {
166 'session_id': saved_session,
167 'instance_url': self.config['instance_url']
168 }
169 return self._auth(config)
170
171 def _acquire_session(self):
172 # only one worker at a time can check session_file
173 auth_success = False
174
175 with open(SESSION_FILE, 'r+') as session_file:
176 with flocked(session_file):
177 logger.info('Successfully locked session file for refresh.')
178
179 saved_session = self._load_session(session_file)
180
181 if self._refresh_ready(saved_session):
Michal Kobusf0046f52019-04-24 12:56:41 +0200182 logger.info('Attempting to refresh session.')
Michal Kobus211ee922019-04-15 17:44:06 +0200183
184 if self._auth(self.config):
185 auth_success = True
186 session_file.truncate(0)
187 session_file.seek(0)
188 session_file.write(self.sf.session_id)
189 logger.info('Refreshed session successfully.')
190 else:
191 logger.error('Failed to refresh session.')
192 else:
193 logger.info('Not refreshing. Reusing session.')
194 auth_success = self._reuse_session(saved_session)
195
Michal Kobusf0046f52019-04-24 12:56:41 +0200196 if auth_success is False:
197 logger.warn('Waiting 30 seconds before next attempt...')
198 time.sleep(30)
199
Michal Kobus211ee922019-04-15 17:44:06 +0200200 return auth_success
201
202 def auth(self):
203 auth_ok = self._acquire_session()
204 while auth_ok is False:
205 auth_ok = self._acquire_session()
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100206
Michal Kobusaa3accf2019-06-05 12:25:09 +0200207 def _get_alert_id(self, labels):
208 alert_id_data = ''
209 for key in sorted(labels):
210 alert_id_data += labels[key].replace(".", "\\.")
Michal Kobus492d8bc2021-02-15 16:54:13 +0100211 return self.hash_func(alert_id_data.encode('utf-8')).hexdigest()
Michal Kobusaa3accf2019-06-05 12:25:09 +0200212
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100213 @sf_auth_retry
214 def _create_case(self, subject, body, labels, alert_id):
215
Michal Kobusaa3accf2019-06-05 12:25:09 +0200216 if alert_id in self._registered_alerts:
Michal Kobusafbf4d02018-11-28 14:18:05 +0100217 logger.warning('Duplicate case for alert: {}.'.format(alert_id))
Michal Kobusaa3accf2019-06-05 12:25:09 +0200218 return 1, self._registered_alerts[alert_id]['Id']
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100219
220 severity = labels.get('severity', 'unknown').upper()
221 payload = {
222 'Subject': subject,
223 'Description': body,
224 'IsMosAlert__c': 'true',
225 'Alert_Priority__c': STATE_MAP.get(severity, '070 Unknown'),
226 'Alert_Host__c': labels.get('host') or labels.get(
227 'instance', 'UNKNOWN'
228 ),
229 'Alert_Service__c': labels.get('service', 'UNKNOWN'),
230 'Environment2__c': self.environment,
231 'Alert_ID__c': alert_id,
232 }
Michal Kobusaf771fc2020-04-29 15:57:16 +0200233 if labels.get('cluster_id') is not None:
234 payload['ClusterId__c'] = labels['cluster_id']
235
Michal Kobusafbf4d02018-11-28 14:18:05 +0100236 logger.info('Try to create case: {}.'.format(payload))
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100237 try:
Michal Kobusafbf4d02018-11-28 14:18:05 +0100238 self.metrics['sf_request_count'].inc()
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100239 case = self.sf.Case.create(payload)
Michal Kobusafbf4d02018-11-28 14:18:05 +0100240 logger.info('Created case: {}.'.format(case))
Michal Kobusaa3accf2019-06-05 12:25:09 +0200241 except sf_exceptions.SalesforceMalformedRequest as ex:
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100242 msg = ex.content[0]['message']
243 err_code = ex.content[0]['errorCode']
244
245 if err_code == 'DUPLICATE_VALUE':
Michal Kobus17726ae2018-11-27 12:59:55 +0100246 logger.warning('Duplicate case: {}.'.format(msg))
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100247 case_id = msg.split()[-1]
Michal Kobusaa3accf2019-06-05 12:25:09 +0200248 self._registered_alerts[alert_id] = {'Id': case_id}
249 return 1, case_id
Michal Kobus27457d42019-02-13 14:06:11 +0100250
251 logger.error('Cannot create case: {}.'.format(msg))
252 self.metrics['sf_error_count'].inc()
253 raise
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100254
Michal Kobusaa3accf2019-06-05 12:25:09 +0200255 self._registered_alerts[alert_id] = {'Id': case['id']}
256 return 0, case['id']
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100257
258 @sf_auth_retry
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100259 def _close_case(self, case_id):
260 logger.info('Try to close case: {}.'.format(case_id))
Michal Kobusafbf4d02018-11-28 14:18:05 +0100261 self.metrics['sf_request_count'].inc()
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100262 update = self.sf.Case.update(
263 case_id,
264 {'Status': 'Auto-solved', 'Alert_ID__c': uuid.uuid4().hex}
265 )
266 logger.info('Closed case: {}.'.format(case_id))
267 return update
268
269 @sf_auth_retry
270 def _create_feed_item(self, subject, body, case_id):
271 feed_item = {'Title': subject, 'ParentId': case_id, 'Body': body}
Michal Kobus2e85ef82021-06-24 18:01:43 +0200272 logger.debug('Creating feed item: {}.'.format(feed_item))
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100273 return self.sf.FeedItem.create(feed_item)
274
275 @sf_auth_retry
276 def _get_case_by_alert_id(self, alert_id):
277 logger.info('Try to get case by alert ID: {}.'.format(alert_id))
278
279 if alert_id in self._registered_alerts:
Michal Kobusaa3accf2019-06-05 12:25:09 +0200280 return self._registered_alerts[alert_id]
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100281 try:
282 return self.sf.Case.get_by_custom_id('Alert_ID__c', alert_id)
Michal Kobusaa3accf2019-06-05 12:25:09 +0200283 except sf_exceptions.SalesforceResourceNotFound:
284 if self._registered_alerts.get(alert_id):
285 del self._registered_alerts[alert_id]
Michal Kobusba987052018-11-30 13:01:08 +0100286
Michal Kobus27457d42019-02-13 14:06:11 +0100287 logger.warning('Alert ID: {} not found.'.format(alert_id))
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100288
Michal Kobus915f3cf2018-12-10 20:09:41 +0100289 def create_case(self, subject, body, labels):
Michal Kobusaa3accf2019-06-05 12:25:09 +0200290 alert_id = self._get_alert_id(labels)
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100291
Michal Kobusaa3accf2019-06-05 12:25:09 +0200292 error_code, case_id = self._create_case(subject, body,
293 labels, alert_id)
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100294
Michal Kobusaa3accf2019-06-05 12:25:09 +0200295 response = {'case_id': case_id, 'alert_id': alert_id}
Michal Kobus915f3cf2018-12-10 20:09:41 +0100296
Michal Kobusaa3accf2019-06-05 12:25:09 +0200297 if error_code == 1:
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100298 response['status'] = 'duplicate'
Michal Kobus915f3cf2018-12-10 20:09:41 +0100299 else:
300 response['status'] = 'created'
Michal Kobus2e85ef82021-06-24 18:01:43 +0200301
302 if self.feed_enabled:
303 self._create_feed_item(subject, body, case_id)
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100304 return response
305
306 def close_case(self, labels):
Michal Kobusaa3accf2019-06-05 12:25:09 +0200307 alert_id = self._get_alert_id(labels)
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100308 case = self._get_case_by_alert_id(alert_id)
309
310 response = {'alert_id': alert_id, 'status': 'resolved'}
311
312 if case is None:
313 return response
314
Michal Kobusaa3accf2019-06-05 12:25:09 +0200315 if self._registered_alerts.get(alert_id):
316 del self._registered_alerts[alert_id]
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100317
Michal Kobusaa3accf2019-06-05 12:25:09 +0200318 response['case_id'] = case['Id']
319 response['closed'] = self._close_case(case['Id'])
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +0100320 return response