Michal Kobus | fc1e773 | 2019-05-16 18:30:48 +0200 | [diff] [blame] | 1 | import datetime |
| 2 | import hashlib |
| 3 | import logging |
| 4 | import os |
| 5 | |
| 6 | from exceptions import SfNotifierError |
| 7 | from settings import (ALLOWED_HASHING, CONFIG_FIELD_MAP, |
| 8 | FEED_UPDATE_INTERVAL) |
| 9 | |
| 10 | |
| 11 | logger = logging.getLogger(__name__) |
| 12 | |
| 13 | |
| 14 | class SalesforceMixin(object): |
| 15 | |
| 16 | @staticmethod |
| 17 | def _hash_func(): |
| 18 | name = os.environ.get('SF_NOTIFIER_ALERT_ID_HASH_FUNC', 'sha256') |
| 19 | if name in ALLOWED_HASHING: |
| 20 | return getattr(hashlib, name) |
| 21 | return hashlib.sha256 |
| 22 | |
| 23 | @staticmethod |
| 24 | def _feed_update_ready(update_time): |
| 25 | now = datetime.datetime.now() |
| 26 | feed_update_interval = datetime.timedelta(hours=FEED_UPDATE_INTERVAL) |
| 27 | return now - update_time >= feed_update_interval |
| 28 | |
| 29 | @staticmethod |
| 30 | def _validate_config(config): |
| 31 | kwargs = {} |
| 32 | |
| 33 | for param, field in CONFIG_FIELD_MAP.iteritems(): |
| 34 | setting_var = param.upper() |
| 35 | env_var = 'SFDC_{}'.format(setting_var) |
| 36 | kwargs[field] = os.environ.get( |
| 37 | env_var, config.get(setting_var)) |
| 38 | |
| 39 | if field == 'domain': |
| 40 | if kwargs[field] in ['true', 'True', True]: |
| 41 | kwargs[field] = 'test' |
| 42 | else: |
| 43 | del kwargs[field] |
| 44 | continue |
| 45 | |
| 46 | if kwargs[field] is None: |
| 47 | msg = ('Invalid config: missing "{}" field or "{}" environment' |
| 48 | ' variable.').format(param, env_var) |
| 49 | logger.error(msg) |
| 50 | raise SfNotifierError(msg) |
| 51 | return kwargs |
| 52 | |
| 53 | @staticmethod |
| 54 | def _load_session(session_file): |
| 55 | lines = session_file.readlines() |
| 56 | |
| 57 | if lines == []: |
| 58 | return |
| 59 | return lines[0] |
| 60 | |
| 61 | @staticmethod |
| 62 | def _fmt_alert_update(case_id, error_code, error_msg=None, now=None): |
| 63 | now = now or datetime.datetime.now() |
| 64 | row = { |
| 65 | 'id': case_id, |
| 66 | 'error_code': error_code, |
| 67 | 'last_update': now |
| 68 | } |
| 69 | if error_msg is not None: |
| 70 | row.update({'error': error_msg}) |
| 71 | return row |
| 72 | |
| 73 | def get_alert_id(self, labels, hash_func=None): |
| 74 | hash_func = hash_func or self.hash_func |
| 75 | alert_id_data = '' |
| 76 | for key in sorted(labels): |
| 77 | alert_id_data += labels[key].replace(".", "\\.") |
| 78 | return hash_func(alert_id_data).hexdigest() |