blob: 182f55d9953697a1b847393ec85d84f6bd5f25ea [file] [log] [blame]
Mateusz Matuszkowiak2820c662018-11-21 12:07:25 +01001# 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
16import json
17from logging.config import dictConfig
18
19from flask import Flask, Response, jsonify, request
20
21from sf_notifier.helpers import alert_fields_and_action
22from sf_notifier.salesforce.client import SalesforceClient
23
24from simple_salesforce.exceptions import SalesforceMalformedRequest
25
26from simple_settings import settings
27
28
29dictConfig(settings.LOGGING)
30
31app = Flask('__name__')
32sf_cli = SalesforceClient(settings.SF_CONFIG)
33
34
35@app.route('/health', methods=['GET'])
36def health():
37 app.logger.info('Health: OK!')
38 return 'OK!'
39
40
41@app.route('/hook', methods=['POST'])
42def 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
77if __name__ == '__main__':
78 app.run()