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
9 # http://www.apache.org/licenses/LICENSE-2.0
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=================================================
19 from flask import Flask, request, Response
20 from time import sleep
28 # list of callback messages
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>"
46 MIME_TEXT="text/plain"
47 MIME_JSON="application/json"
48 CAUGHT_EXCEPTION="Caught exception: "
49 SERVER_ERROR="Server error :"
57 ### Callback interface, for control
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,
64 def receiveresponse(id):
66 global cntr_msg_fetched
69 if ((id in msg_callbacks.keys()) and (len(msg_callbacks[id]) > 0)):
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))
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,
89 def receiveresponse_all(id):
91 global cntr_msg_fetched
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])
98 print("Fetching all msgs for id: "+id+", msg="+str(msg))
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()
108 return json.dumps(msg),200
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):
117 global cntr_msg_callbacks
120 print("Received callback for id: "+id +", content-type="+request.content_type)
122 if (request.content_type == MIME_JSON):
124 msg = json.loads(data)
125 print("Payload(json): "+str(msg))
128 print("Payload(content-type="+request.content_type+"). Setting empty json as payload")
129 except Exception as e:
131 print("(Exception) Payload does not contain any json, setting empty json as payload")
132 traceback.print_exc()
134 cntr_msg_callbacks += 1
135 if (id in msg_callbacks.keys()):
136 msg_callbacks[id].append(msg)
139 msg_callbacks[id].append(msg)
141 if (id in cntr_callbacks.keys()):
142 cntr_callbacks[id][0] += 1
144 cntr_callbacks[id]=[]
145 cntr_callbacks[id].append(1)
146 cntr_callbacks[id].append(0)
148 except Exception as e:
149 print(CAUGHT_EXCEPTION+str(e))
150 traceback.print_exc()
155 ### Functions for test ###
157 # Dump the whole db of current callbacks
158 # URI and parameter, (GET): /db
159 # response: message + 200
160 @app.route(DUMP_ALL_URL,
163 return json.dumps(msg_callbacks),200
165 ### Functions for metrics read out ###
167 @app.route('/counter/received_callbacks',
169 def requests_submitted():
170 req_id = request.args.get('id')
172 return Response(str(cntr_msg_callbacks), status=200, mimetype=MIME_TEXT)
174 if (req_id in cntr_callbacks.keys()):
175 return Response(str(cntr_callbacks[req_id][0]), status=200, mimetype=MIME_TEXT)
177 return Response(str("0"), status=200, mimetype=MIME_TEXT)
179 @app.route('/counter/fetched_callbacks',
181 def requests_fetched():
182 req_id = request.args.get('id')
184 return Response(str(cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
186 if (req_id in cntr_callbacks.keys()):
187 return Response(str(cntr_callbacks[req_id][1]), status=200, mimetype=MIME_TEXT)
189 return Response(str("0"), status=200, mimetype=MIME_TEXT)
191 @app.route('/counter/current_messages',
193 def current_messages():
194 req_id = request.args.get('id')
196 return Response(str(cntr_msg_callbacks-cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
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)
201 return Response(str("0"), status=200, mimetype=MIME_TEXT)
206 # Reset all messsages and counters
208 methods=['GET', 'POST', 'PUT'])
211 global cntr_msg_fetched
212 global cntr_msg_callbacks
218 return Response('OK', status=200, mimetype=MIME_TEXT)
220 ### Main function ###
222 if __name__ == "__main__":
223 app.run(port=HOST_PORT, host=HOST_IP)