Mateusz Matuszkowiak | 2820c66 | 2018-11-21 12:07:25 +0100 | [diff] [blame^] | 1 | # Copyright 2018: Mirantis Inc. |
| 2 | # All Rights Reserved. |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 | # not use this file except in compliance with the License. You may obtain |
| 6 | # a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | # License for the specific language governing permissions and limitations |
| 14 | # under the License. |
| 15 | |
| 16 | import hashlib |
| 17 | import logging |
| 18 | import os |
| 19 | import uuid |
| 20 | |
| 21 | import requests |
| 22 | |
| 23 | from simple_salesforce import Salesforce |
| 24 | from simple_salesforce import exceptions as sf_exceptions |
| 25 | |
| 26 | |
| 27 | STATE_MAP = { |
| 28 | 'OK': '060 Informational', |
| 29 | 'UP': '060 Informational', |
| 30 | 'UNKNOWN': '070 Unknown', |
| 31 | 'WARNING': '080 Warning', |
| 32 | 'MINOR': '080 Warning', |
| 33 | 'MAJOR': '090 Critical', |
| 34 | 'CRITICAL': '090 Critical', |
| 35 | 'DOWN': '090 Critical', |
| 36 | 'UNREACHABLE': '090 Critical', |
| 37 | } |
| 38 | |
| 39 | CONFIG_FIELD_MAP = { |
| 40 | 'auth_url': 'instance', |
| 41 | 'username': 'username', |
| 42 | 'password': 'password', |
| 43 | 'organization_id': 'organizationId', |
| 44 | 'environment_id': 'environment_id', |
| 45 | 'sandbox_enabled': 'domain', |
| 46 | } |
| 47 | |
| 48 | logger = logging.getLogger(__name__) |
| 49 | |
| 50 | |
| 51 | def sf_auth_retry(method): |
| 52 | def wrapper(self, *args, **kwargs): |
| 53 | try: |
| 54 | return method(self, *args, **kwargs) |
| 55 | except sf_exceptions.SalesforceExpiredSession: |
| 56 | logger.warning('Salesforce session expired.') |
| 57 | self._auth() |
| 58 | return method(self, *args, **kwargs) |
| 59 | return wrapper |
| 60 | |
| 61 | |
| 62 | class SfNotifierError(Exception): |
| 63 | def __init__(self, message, errors): |
| 64 | super(SfNotifierError, self).__init__(message) |
| 65 | self.errors = errors |
| 66 | |
| 67 | |
| 68 | class SalesforceClient(object): |
| 69 | |
| 70 | def __init__(self, config): |
| 71 | self.session = requests.Session() |
| 72 | self.config = self._validate_config(config) |
| 73 | self.environment = self.config.pop('environment_id') |
| 74 | self._auth() |
| 75 | self._registered_alerts = {} |
| 76 | |
| 77 | def _validate_config(self, config): |
| 78 | kwargs = {'session': self.session} |
| 79 | |
| 80 | for param, field in CONFIG_FIELD_MAP.iteritems(): |
| 81 | setting_var = param.upper() |
| 82 | env_var = 'SFDC_{}'.format(setting_var) |
| 83 | kwargs[field] = os.environ.get( |
| 84 | env_var, getattr(config, setting_var, None)) |
| 85 | |
| 86 | if field == 'domain': |
| 87 | kwargs[field] = kwargs[field] and 'test' |
| 88 | continue |
| 89 | |
| 90 | if kwargs[field] is None: |
| 91 | msg = ('Invalid config: missing "{}" field or "{}" environment' |
| 92 | ' variable.').format(param, env_var) |
| 93 | logger.error(msg) |
| 94 | raise SfNotifierError(msg) |
| 95 | return kwargs |
| 96 | |
| 97 | def _auth(self): |
| 98 | self.sf = Salesforce(**self.config) |
| 99 | logger.info('Salesforce authentication successful.') |
| 100 | |
| 101 | def _get_alert_id(self, labels): |
| 102 | alert_id_data = '' |
| 103 | for key in sorted(labels): |
| 104 | alert_id_data += labels[key].replace(".", "\\.") |
| 105 | return hashlib.sha256(alert_id_data).hexdigest() |
| 106 | |
| 107 | @sf_auth_retry |
| 108 | def _create_case(self, subject, body, labels, alert_id): |
| 109 | |
| 110 | if alert_id in self._registered_alerts: |
| 111 | logger.info('Duplicate case for alert: {}.'.format(alert_id)) |
| 112 | return 1, self._registered_alerts[alert_id]['Id'] |
| 113 | |
| 114 | severity = labels.get('severity', 'unknown').upper() |
| 115 | payload = { |
| 116 | 'Subject': subject, |
| 117 | 'Description': body, |
| 118 | 'IsMosAlert__c': 'true', |
| 119 | 'Alert_Priority__c': STATE_MAP.get(severity, '070 Unknown'), |
| 120 | 'Alert_Host__c': labels.get('host') or labels.get( |
| 121 | 'instance', 'UNKNOWN' |
| 122 | ), |
| 123 | 'Alert_Service__c': labels.get('service', 'UNKNOWN'), |
| 124 | 'Environment2__c': self.environment, |
| 125 | 'Alert_ID__c': alert_id, |
| 126 | } |
| 127 | logger.info('Try to create case: {}'.format(payload)) |
| 128 | try: |
| 129 | case = self.sf.Case.create(payload) |
| 130 | except sf_exceptions.SalesforceMalformedRequest as ex: |
| 131 | msg = ex.content[0]['message'] |
| 132 | err_code = ex.content[0]['errorCode'] |
| 133 | |
| 134 | if err_code == 'DUPLICATE_VALUE': |
| 135 | logger.info('Duplicate case: {}.'.format(msg)) |
| 136 | case_id = msg.split()[-1] |
| 137 | self._registered_alerts[alert_id] = {'Id': case_id} |
| 138 | return 1, case_id |
| 139 | else: |
| 140 | raise |
| 141 | |
| 142 | self._registered_alerts[alert_id] = {'Id': case['id']} |
| 143 | return 0, case['id'] |
| 144 | |
| 145 | @sf_auth_retry |
| 146 | def _get_case(self, case_id): |
| 147 | return self.sf.Case.get(case_id) |
| 148 | |
| 149 | @sf_auth_retry |
| 150 | def _update_case(self, case_id, data): |
| 151 | return self.sf.Case.update(case_id, data) |
| 152 | |
| 153 | @sf_auth_retry |
| 154 | def _close_case(self, case_id): |
| 155 | logger.info('Try to close case: {}.'.format(case_id)) |
| 156 | update = self.sf.Case.update( |
| 157 | case_id, |
| 158 | {'Status': 'Auto-solved', 'Alert_ID__c': uuid.uuid4().hex} |
| 159 | ) |
| 160 | logger.info('Closed case: {}.'.format(case_id)) |
| 161 | return update |
| 162 | |
| 163 | @sf_auth_retry |
| 164 | def _create_feed_item(self, subject, body, case_id): |
| 165 | feed_item = {'Title': subject, 'ParentId': case_id, 'Body': body} |
| 166 | return self.sf.FeedItem.create(feed_item) |
| 167 | |
| 168 | @sf_auth_retry |
| 169 | def _get_case_by_alert_id(self, alert_id): |
| 170 | logger.info('Try to get case by alert ID: {}.'.format(alert_id)) |
| 171 | |
| 172 | if alert_id in self._registered_alerts: |
| 173 | return self._registered_alerts[alert_id] |
| 174 | try: |
| 175 | return self.sf.Case.get_by_custom_id('Alert_ID__c', alert_id) |
| 176 | except sf_exceptions.SalesforceResourceNotFound: |
| 177 | logger.warning('Alert ID: {} was already solved.'.format(alert_id)) |
| 178 | |
| 179 | def create_case(self, subject, body, status, labels): |
| 180 | alert_id = self._get_alert_id(labels) |
| 181 | |
| 182 | error_code, case_id = self._create_case(subject, body, |
| 183 | labels, alert_id) |
| 184 | |
| 185 | response = {'case_id': case_id, 'alert_id': alert_id, |
| 186 | 'status': 'created'} |
| 187 | |
| 188 | if error_code != 2: |
| 189 | self._create_feed_item(subject, body, case_id) |
| 190 | if error_code == 1: |
| 191 | response['status'] = 'duplicate' |
| 192 | return response |
| 193 | |
| 194 | def close_case(self, labels): |
| 195 | alert_id = self._get_alert_id(labels) |
| 196 | case = self._get_case_by_alert_id(alert_id) |
| 197 | |
| 198 | response = {'alert_id': alert_id, 'status': 'resolved'} |
| 199 | |
| 200 | if case is None: |
| 201 | return response |
| 202 | |
| 203 | if self._registered_alerts.get(alert_id): |
| 204 | del self._registered_alerts[alert_id] |
| 205 | |
| 206 | response['case_id'] = case['Id'] |
| 207 | response['closed'] = self._close_case(case['Id']) |
| 208 | return response |