Convert file endlines to Unix (LF)
[pti/o2.git] / mock_smo / mock_smo / entrypoints / mock_smo.py
1 # Copyright (C) 2021 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14
15 import json
16 import redis
17 import http.client
18 from flask import Flask, request
19 from flask.helpers import url_for
20
21 import mock_smo.config as config
22 import mock_smo.logging as logging
23 logger = logging.get_logger(__name__)
24
25 apibase = config.get_o2ims_api_base()
26 app = Flask(__name__)
27
28 r = redis.Redis(**config.get_redis_host_and_port())
29 REDIS_SUB_KEY = 'mock_smo_sub_key'
30 REDIS_O2IMS_URL = 'mock_smo_o2ims_url'
31
32
33 @app.route('/', methods=['GET', 'POST'])
34 def index():
35     if request.method == 'POST':
36         url = request.form['url']
37         consumerSubscriptionId = request.form['consumerSubId']
38         sub_id = subscription_ims(url, consumerSubscriptionId)
39         return """
40 <h1>Subscribed O2IMS</h1>
41 <h3>Subscription ID: %s</h3>
42 <h3>Subscribed O2IMS URL: %s</h3>
43 <a href="%s">
44    <input type="button" value="Unsubscription" />
45 </a>
46 """ % (sub_id, url, url_for('unsubscription'))
47     return """
48 <h1>Subscribe O2IMS</h1>
49 <form method="POST">
50     <label for="url">O2 IMS URL: </label>
51     <input type="text" id="url" name="url" value="api:80"></br></br>
52     <label for="consumerSubId">Consumer Sub ID: </label>
53     <input type="text" id="consumerSubId" name="consumerSubId"></br></br>
54     <input type="submit" value="Submit">
55 </form>
56 """
57
58
59 @app.route('/unsubscription')
60 def unsubscription():
61     sub_key = r.get(REDIS_SUB_KEY)
62     logger.info('Subscription key is {}'.format(sub_key))
63     if sub_key is None:
64         return '<h1>Already unsubscribed</h1>'
65     url = r.get(REDIS_O2IMS_URL).decode('utf-8')
66     logger.info('O2 IMS API is: {}'.format(url))
67     unsubscription_ims(url, sub_key.decode('utf-8'))
68     r.delete(REDIS_O2IMS_URL)
69     r.delete(REDIS_SUB_KEY)
70     return """
71 <h1>Unsubscribed O2IMS</h1>
72 <a href="/">
73    <input type="button" value="Go Back" />
74 </a>
75 """
76
77
78 @app.route('/callback', methods=['POST'])
79 def callback():
80     logger.info('Callback data: {}'.format(request.get_data()))
81     return '', 202
82
83
84 @app.route('/registration', methods=['POST'])
85 def registration():
86     logger.info('Registration data: {}'.format(request.get_data()))
87     return '', 200
88
89
90 def subscription_ims(url, consumerSubscriptionId):
91     sub_key = r.get(REDIS_SUB_KEY)
92     logger.info('Subscription key is {}'.format(sub_key))
93     if sub_key is not None:
94         return sub_key.decode('utf-8')
95
96     logger.info(request.host_url)
97     conn = http.client.HTTPConnection(url)
98     headers = {'Content-type': 'application/json'}
99     post_val = {
100         'callback': 'http://mock_smo:80' + url_for('callback'),
101         'consumerSubscriptionId': consumerSubscriptionId,
102         'filter': '["pserver"]'  # '["pserver","pserver_mem"]'
103     }
104     json_val = json.dumps(post_val)
105     conn.request('POST', apibase+'/subscriptions', json_val, headers)
106     resp = conn.getresponse()
107     data = resp.read().decode('utf-8')
108     logger.info('Subscription response: {} {}, data: {}'.format(
109         resp.status, resp.reason, data))
110     json_data = json.loads(data)
111
112     r.set(REDIS_SUB_KEY, json_data['subscriptionId'])
113     r.set(REDIS_O2IMS_URL, url)
114     return json_data['subscriptionId']
115
116
117 def unsubscription_ims(url, subId):
118     conn = http.client.HTTPConnection(url)
119     conn.request('DELETE', apibase + '/subscriptions/' + subId)
120     resp = conn.getresponse()
121     logger.info('Unsubscription response: {} {}'.format(
122         resp.status, resp.reason))