Merge "Further updates to the auto-test environment"
[nonrtric.git] / test / cr / 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
20 from time import sleep
21 import time
22 import datetime
23 import json
24 from flask import Flask
25 from flask import Response
26 import traceback
27
28 app = Flask(__name__)
29
30 # list of callback messages
31 msg_callbacks={}
32
33 # Server info
34 HOST_IP = "::"
35 HOST_PORT = 8090
36
37 # Metrics vars
38 cntr_msg_callbacks=0
39 cntr_msg_fetched=0
40
41 # Request and response constants
42 CALLBACK_URL="/callbacks/<string:id>"
43 APP_READ_URL="/get-event/<string:id>"
44
45 MIME_TEXT="text/plain"
46 MIME_JSON="application/json"
47 CAUGHT_EXCEPTION="Caught exception: "
48 SERVER_ERROR="Server error :"
49
50 #I'm alive function
51 @app.route('/',
52     methods=['GET'])
53 def index():
54     return 'OK', 200
55
56 ### Callback interface, for control
57
58 # Fetch the oldest callback message for an id
59 # URI and parameter, (GET): /get-event/<id>
60 # response: message + 200 or 204
61 @app.route(APP_READ_URL,
62     methods=['GET'])
63 def receiveresponse(id):
64     global msg_callbacks
65     global cntr_msg_fetched
66
67     try:
68         if ((id in msg_callbacks.keys()) and (len(msg_callbacks[id]) > 0)):
69             cntr_msg_fetched+=1
70             msg=str(msg_callbacks[id][0])
71             print("Fetching msg for id: "+id+", msg="+msg)
72             del msg_callbacks[id][0]
73             return msg,200
74         print("No messages for id: "+id)
75     except Exception as e:
76         print(CAUGHT_EXCEPTION+str(e))
77
78     return "",204
79
80
81 # Receive a callback message
82 # URI and payload, (PUT or POST): /callbacks/<id> <json array of response messages>
83 # response: OK 200 or 500 for other errors
84 @app.route(CALLBACK_URL,
85     methods=['PUT','POST'])
86 def events_write(id):
87     global msg_callbacks
88     global cntr_msg_callbacks
89
90     try:
91         print("Received callback for id: "+id +", content-type="+request.content_type)
92         try:
93             print("data:"+request.get_data)
94             if (request.content_type == MIME_JSON):
95                 msg = request.json
96                 print("Payload(json): "+str(msg))
97             elif (request.content_type == MIME_TEXT):
98                 msg= request.form
99                 print("Payload(text): "+str(msg))
100             else:
101                 msg="\"\""
102                 print("Payload(content-type="+request.content_type+"). Setting data to empty, quoted, string")
103         except:
104             msg="\"\""
105             print("Payload does not contain any json or text data, setting empty string as payload")
106
107         cntr_msg_callbacks += 1
108         if (id in msg_callbacks.keys()):
109             msg_callbacks[id].append(msg)
110         else:
111             msg_callbacks[id]=[]
112             msg_callbacks[id].append(msg)
113     except Exception as e:
114         print(CAUGHT_EXCEPTION+str(e))
115         return 'OK',500
116
117     return 'OK',200
118
119
120 ### Functions for metrics read out ###
121
122 @app.route('/counter/received_callbacks',
123     methods=['GET'])
124 def requests_submitted():
125     return Response(str(cntr_msg_callbacks), status=200, mimetype=MIME_TEXT)
126
127 @app.route('/counter/fetched_callbacks',
128     methods=['GET'])
129 def requests_fetched():
130     return Response(str(cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
131
132 @app.route('/counter/current_messages',
133     methods=['GET'])
134 def current_messages():
135     return Response(str(cntr_msg_callbacks-cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
136
137
138
139 ### Admin ###
140
141 # Reset all messsages and counters
142 @app.route('/reset',
143     methods=['GET', 'POST', 'PUT'])
144 def reset():
145     global msg_callbacks
146     global cntr_msg_fetched
147     global cntr_msg_callbacks
148
149     msg_callbacks={}
150     cntr_msg_fetched=0
151     cntr_msg_callbacks=0
152
153     return Response('OK', status=200, mimetype=MIME_TEXT)
154
155 ### Main function ###
156
157 if __name__ == "__main__":
158     app.run(port=HOST_PORT, host=HOST_IP)