blob: bc6e28f9203ee2c4fc81147fa62a064d83f36f52 [file] [log] [blame]
BjornMagnussonXA80a92002020-03-19 14:31:06 +01001
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
19from flask import Flask, request
20from time import sleep
21import time
22import datetime
23import json
24from flask import Flask
25from flask import Response
26import traceback
27
28app = Flask(__name__)
29
30# list of callback messages
31msg_callbacks={}
32
33# Server info
BjornMagnussonXA72667f12020-04-24 09:20:18 +020034HOST_IP = "::"
ecaiyanlinux113bf092020-08-01 14:05:17 +000035HOST_PORT = 2222
BjornMagnussonXA80a92002020-03-19 14:31:06 +010036
37# Metrics vars
38cntr_msg_callbacks=0
39cntr_msg_fetched=0
40
41# Request and response constants
42CALLBACK_URL="/callbacks/<string:id>"
43APP_READ_URL="/get-event/<string:id>"
44
45MIME_TEXT="text/plain"
46MIME_JSON="application/json"
47CAUGHT_EXCEPTION="Caught exception: "
48SERVER_ERROR="Server error :"
49
50#I'm alive function
51@app.route('/',
52 methods=['GET'])
53def 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'])
63def 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'])
86def 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:
BjornMagnussonXA80a92002020-03-19 14:31:06 +010093 if (request.content_type == MIME_JSON):
94 msg = request.json
95 print("Payload(json): "+str(msg))
96 elif (request.content_type == MIME_TEXT):
97 msg= request.form
98 print("Payload(text): "+str(msg))
99 else:
100 msg="\"\""
101 print("Payload(content-type="+request.content_type+"). Setting data to empty, quoted, string")
102 except:
103 msg="\"\""
BjornMagnussonXA70e878f2020-05-11 14:11:30 +0200104 print("(Exception) Payload does not contain any json or text data, setting empty string as payload")
BjornMagnussonXA80a92002020-03-19 14:31:06 +0100105
106 cntr_msg_callbacks += 1
107 if (id in msg_callbacks.keys()):
108 msg_callbacks[id].append(msg)
109 else:
110 msg_callbacks[id]=[]
111 msg_callbacks[id].append(msg)
112 except Exception as e:
113 print(CAUGHT_EXCEPTION+str(e))
114 return 'OK',500
115
116 return 'OK',200
117
118
119### Functions for metrics read out ###
120
121@app.route('/counter/received_callbacks',
122 methods=['GET'])
123def requests_submitted():
124 return Response(str(cntr_msg_callbacks), status=200, mimetype=MIME_TEXT)
125
126@app.route('/counter/fetched_callbacks',
127 methods=['GET'])
128def requests_fetched():
129 return Response(str(cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
130
131@app.route('/counter/current_messages',
132 methods=['GET'])
133def current_messages():
134 return Response(str(cntr_msg_callbacks-cntr_msg_fetched), status=200, mimetype=MIME_TEXT)
135
136
137
138### Admin ###
139
140# Reset all messsages and counters
141@app.route('/reset',
142 methods=['GET', 'POST', 'PUT'])
143def reset():
144 global msg_callbacks
145 global cntr_msg_fetched
146 global cntr_msg_callbacks
147
148 msg_callbacks={}
149 cntr_msg_fetched=0
150 cntr_msg_callbacks=0
151
152 return Response('OK', status=200, mimetype=MIME_TEXT)
153
154### Main function ###
155
156if __name__ == "__main__":
157 app.run(port=HOST_PORT, host=HOST_IP)