Merge "Add docker-compose file for ECS"
[nonrtric.git] / test / cr / app / cr.py
1
2 #  ============LICENSE_START===============================================
3 #  Copyright (C) 2020 Nordix Foundation. All rights reserved.
4 #  ========================================================================
5 #  Licensed under the Apache License, Version 2.0 (the "License");
6 #  you may not use this file except in compliance with the License.
7 #  You may obtain a copy of the License at
8 #
9 #       http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #  Unless required by applicable law or agreed to in writing, software
12 #  distributed under the License is distributed on an "AS IS" BASIS,
13 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 #  See the License for the specific language governing permissions and
15 #  limitations under the License.
16 #  ============LICENSE_END=================================================
17 #
18
19 from flask import Flask, request, Response
20 from time import sleep
21 import time
22 import datetime
23 import json
24 import traceback
25
26 app = Flask(__name__)
27
28 # list of callback messages
29 msg_callbacks={}
30
31 # Server info
32 HOST_IP = "::"
33 HOST_PORT = 2222
34
35 # Metrics vars
36 cntr_msg_callbacks=0
37 cntr_msg_fetched=0
38 cntr_callbacks={}
39
40 # Request and response constants
41 CALLBACK_URL="/callbacks/<string:id>"
42 APP_READ_URL="/get-event/<string:id>"
43 APP_READ_ALL_URL="/get-all-events/<string:id>"
44 DUMP_ALL_URL="/db"
45
46 MIME_TEXT="text/plain"
47 MIME_JSON="application/json"
48 CAUGHT_EXCEPTION="Caught exception: "
49 SERVER_ERROR="Server error :"
50
51 #I'm alive function
52 @app.route('/',
53     methods=['GET'])
54 def index():
55     return 'OK', 200
56
57 ### Callback interface, for control
58
59 # Fetch the oldest callback message for an id
60 # URI and parameter, (GET): /get-event/<id>
61 # response: message + 200 or just 204 or just 500(error)
62 @app.route(APP_READ_URL,
63     methods=['GET'])
64 def receiveresponse(id):
65     global msg_callbacks
66     global cntr_msg_fetched
67
68     try:
69         if ((id in msg_callbacks.keys()) and (len(msg_callbacks[id]) > 0)):
70             cntr_msg_fetched+=1
71             cntr_callbacks[id][1]+=1
72             msg=msg_callbacks[id][0]
73             print("Fetching msg for id: "+id+", msg="+str(msg))
74             del msg_callbacks[id][0]
75             return json.dumps(msg),200
76         print("No messages for id: "+id)
77     except Exception as e:
78         print(CAUGHT_EXCEPTION+str(e))
79         traceback.print_exc()
80         return "",500
81
82     return "",204
83
84 # Fetch all callback message for an id in an array
85 # URI and parameter, (GET): /get-all-events/<id>
86 # response: message + 200 or just 500(error)
87 @app.route(APP_READ_ALL_URL,
88     methods=['GET'])
89 def receiveresponse_all(id):
90     global msg_callbacks
91     global cntr_msg_fetched
92
93     try:
94         if ((id in msg_callbacks.keys()) and (len(msg_callbacks[id]) > 0)):
95             cntr_msg_fetched+=len(msg_callbacks[id])
96             cntr_callbacks[id][1]+=len(msg_callbacks[id])
97             msg=msg_callbacks[id]
98             print("Fetching all msgs for id: "+id+", msg="+str(msg))
99             del msg_callbacks[id]
100             return json.dumps(msg),200
101         print("No messages for id: "+id)
102     except Exception as e:
103         print(CAUGHT_EXCEPTION+str(e))
104         traceback.print_exc()
105         return "",500
106
107     msg=[]
108     return json.dumps(msg),200
109
110 # Receive a callback message
111 # URI and payload, (PUT or POST): /callbacks/<id> <json messages>
112 # response: OK 200 or 500 for other errors
113 @app.route(CALLBACK_URL,
114     methods=['PUT','POST'])
115 def events_write(id):
116     global msg_callbacks
117     global cntr_msg_callbacks
118
119     try:
120         print("Received callback for id: "+id +", content-type="+request.content_type)
121         try:
122             if (request.content_type == MIME_JSON):
123                 data = request.data
124                 msg = json.loads(data)
125                 print("Payload(json): "+str(msg))
126             else:
127                 msg={}
128                 print("Payload(content-type="+request.content_type+"). Setting empty json as payload")
129         except Exception as e:
130             msg={}
131             print("(Exception) Payload does not contain any json, setting empty json as payload")
132             traceback.print_exc()
133
134         cntr_msg_callbacks += 1
135         if (id in msg_callbacks.keys()):
136             msg_callbacks[id].append(msg)
137         else:
138             msg_callbacks[id]=[]
139             msg_callbacks[id].append(msg)
140
141         if (id in cntr_callbacks.keys()):
142             cntr_callbacks[id][0] += 1
143         else:
144             cntr_callbacks[id]=[]
145             cntr_callbacks[id].append(1)
146             cntr_callbacks[id].append(0)
147
148     except Exception as e:
149         print(CAUGHT_EXCEPTION+str(e))
150         traceback.print_exc()
151         return 'NOTOK',500
152
153     return 'OK',200
154
155 ### Functions for test ###
156
157 # Dump the whole db of current callbacks
158 # URI and parameter, (GET): /db
159 # response: message + 200
160 @app.route(DUMP_ALL_URL,
161     methods=['GET'])
162 def dump_db():
163     return json.dumps(msg_callbacks),200
164
165 ### Functions for metrics read out ###
166
167 @app.route('/counter/received_callbacks',
168     methods=['GET'])
169 def requests_submitted():
170     req_id = request.args.get('id')
171     if (req_id is None):
172         return Response(str(cntr_msg_callbacks), status=200, mimetype=MIME_TEXT)
173
174     if (req_id in cntr_callbacks.keys()):
175         return Response(str(cntr_callbacks[req_id][0]), status=200, mimetype=MIME_TEXT)
176     else:
177         return Response(str("0"), status=200, mimetype=MIME_TEXT)
178
179 @app.route('/counter/fetched_callbacks',
180     methods=['GET'])
181 def requests_fetched():
182     req_id = request.args.get('id')
183     if (req_id is None):
184         return Response(str(cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
185
186     if (req_id in cntr_callbacks.keys()):
187         return Response(str(cntr_callbacks[req_id][1]), status=200, mimetype=MIME_TEXT)
188     else:
189         return Response(str("0"), status=200, mimetype=MIME_TEXT)
190
191 @app.route('/counter/current_messages',
192     methods=['GET'])
193 def current_messages():
194     req_id = request.args.get('id')
195     if (req_id is None):
196         return Response(str(cntr_msg_callbacks-cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
197
198     if (req_id in cntr_callbacks.keys()):
199         return Response(str(cntr_callbacks[req_id][0]-cntr_callbacks[req_id][1]), status=200, mimetype=MIME_TEXT)
200     else:
201         return Response(str("0"), status=200, mimetype=MIME_TEXT)
202
203
204 ### Admin ###
205
206 # Reset all messsages and counters
207 @app.route('/reset',
208     methods=['GET', 'POST', 'PUT'])
209 def reset():
210     global msg_callbacks
211     global cntr_msg_fetched
212     global cntr_msg_callbacks
213
214     msg_callbacks={}
215     cntr_msg_fetched=0
216     cntr_msg_callbacks=0
217
218     return Response('OK', status=200, mimetype=MIME_TEXT)
219
220 ### Main function ###
221
222 if __name__ == "__main__":
223     app.run(port=HOST_PORT, host=HOST_IP)