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 json |
| 17 | from logging.config import dictConfig |
| 18 | |
| 19 | from flask import Flask, Response, jsonify, request |
| 20 | |
| 21 | from sf_notifier.helpers import alert_fields_and_action |
| 22 | from sf_notifier.salesforce.client import SalesforceClient |
| 23 | |
| 24 | from simple_salesforce.exceptions import SalesforceMalformedRequest |
| 25 | |
| 26 | from simple_settings import settings |
| 27 | |
| 28 | |
| 29 | dictConfig(settings.LOGGING) |
| 30 | |
| 31 | app = Flask('__name__') |
| 32 | sf_cli = SalesforceClient(settings.SF_CONFIG) |
| 33 | |
| 34 | |
| 35 | @app.route('/health', methods=['GET']) |
| 36 | def health(): |
| 37 | app.logger.info('Health: OK!') |
| 38 | return 'OK!' |
| 39 | |
| 40 | |
| 41 | @app.route('/hook', methods=['POST']) |
| 42 | def webhook_receiver(): |
| 43 | |
| 44 | try: |
| 45 | data = json.loads(request.data) |
| 46 | except ValueError: |
| 47 | return Response(json.dumps({'error': 'Invalid request data.'}), |
| 48 | status=400, |
| 49 | mimetype='application/json') |
| 50 | |
| 51 | app.logger.info('Received requests: {}'.format(data)) |
| 52 | |
| 53 | cases = [] |
| 54 | for alert in data['alerts']: |
| 55 | try: |
| 56 | fields, action = alert_fields_and_action(alert) |
| 57 | except KeyError as key: |
| 58 | msg = 'Alert misses {} key.'.format(key) |
| 59 | app.logger.error(msg) |
| 60 | return Response(json.dumps({'error': msg}), |
| 61 | status=400, |
| 62 | mimetype='application/json') |
| 63 | |
| 64 | if fields: |
| 65 | try: |
| 66 | cases.append(getattr(sf_cli, action)(*fields)) |
| 67 | except SalesforceMalformedRequest: |
| 68 | return Response(json.dumps({'error': 'Request failure.'}), |
| 69 | status=500, |
| 70 | mimetype='application/json') |
| 71 | |
| 72 | if len(cases) == 1: |
| 73 | return jsonify(cases[0]) |
| 74 | return jsonify(cases) |
| 75 | |
| 76 | |
| 77 | if __name__ == '__main__': |
| 78 | app.run() |