1 # ============LICENSE_START===============================================
2 # Copyright (C) 2021 Nordix Foundation. All rights reserved.
3 # ========================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 # ============LICENSE_END=================================================
25 from pathlib import Path
26 from flask import Flask, escape, request, Response
27 from jsonschema import validate
28 from var_declaration import policy_instances, policy_types, policy_status, callbacks, forced_settings, policy_fingerprint, hosts_set, data_delivery_counter, app
29 from maincommon import check_apipath, apipath, get_supported_interfaces_response, extract_host_name
32 TEXT_PLAIN='text/plain'
36 # app is created in var_declarations
38 import payload_logging # app var need to be initialized
41 @app.route('/', methods=['GET'])
44 return Response("OK", 200, mimetype=TEXT_PLAIN)
46 #Return the current and all supported yamls for the this container
47 @app.route('/container_interfaces', methods=['GET'])
48 def container_interfaces():
50 return get_supported_interfaces_response()
52 #Delete all created instances and status
53 @app.route('/deleteinstances', methods=['POST'])
54 def delete_instances():
56 for i in policy_instances.keys():
57 policy_instances[i]={}
60 forced_settings['code']=None
61 forced_settings['delay']=None
62 policy_fingerprint.clear()
63 return Response("All policy instances deleted", 200, mimetype=TEXT_PLAIN)
65 #Delete all - all reset
66 @app.route('/deleteall', methods=['POST'])
68 global data_delivery_counter
70 policy_instances.clear()
74 forced_settings['code']=None
75 forced_settings['delay']=None
76 policy_fingerprint.clear()
77 data_delivery_counter=0
78 return Response("All policy instances and types deleted", 200, mimetype=TEXT_PLAIN)
81 @app.route('/policytype', methods=['PUT'])
84 policy_type_id=request.args.get('id')
85 if (policy_type_id is None):
86 return Response('Parameter <id> missing in request', status=400, mimetype=TEXT_PLAIN)
90 data = json.loads(data)
92 return Response("The policy type is corrupt or missing", 400, mimetype=TEXT_PLAIN)
94 if ('policySchema' not in data.keys()):
95 return Response("The policy type atribute policySchema is missing", 400, mimetype=TEXT_PLAIN)
98 if (policy_type_id in policy_types.keys()):
100 if (len(policy_instances[policy_type_id]) > 0):
101 return Response("The policy type already exists and instances exists", 400, mimetype=TEXT_PLAIN)
103 policy_types[policy_type_id]=data
104 policy_instances[policy_type_id]={}
105 return Response("Policy type " + policy_type_id + " is OK.", retcode, mimetype=TEXT_PLAIN)
107 #Delete a policy type
108 @app.route('/policytype', methods=['DELETE'])
109 def del_policytype():
111 policy_type_id=request.args.get('id')
112 if (policy_type_id is None):
113 return Response('Parameter <id> missing in request', status=400, mimetype=TEXT_PLAIN)
115 if (policy_type_id in policy_types.keys()):
116 if (len(policy_instances[policy_type_id]) > 0):
117 return Response("The policy type already exists and instances exists", 400, mimetype=TEXT_PLAIN)
119 del policy_types[policy_type_id]
120 del policy_instances[policy_type_id]
121 return Response("Policy type " + policy_type_id + " is OK.", 204, mimetype=TEXT_PLAIN)
123 return Response("Policy type " + policy_type_id + " not found.", 204, mimetype=TEXT_PLAIN)
126 # Get all policy type ids
127 @app.route('/policytypes', methods=['GET'])
128 def get_policytype_ids():
130 return (json.dumps(list(policy_instances.keys())), 200)
133 #Set force response for one A1 response
134 #/forceresponse?code=<responsecode>
135 @app.route('/forceresponse', methods=['POST'])
139 forced_settings['code']=request.args.get('code')
141 forced_settings['code']=None
142 return Response("Force response code: " + str(forced_settings['code']) + " set for one single A1 response", 200, mimetype=TEXT_PLAIN)
144 #Set force delay response, in seconds, for all A1 responses
145 #/froceesponse?delay=<seconds>
146 @app.route('/forcedelay', methods=['POST'])
150 forced_settings['delay']=request.args.get('delay')
152 forced_settings['delay']=None
153 return Response("Force delay: " + str(forced_settings['delay']) + " sec set for all A1 responses", 200, mimetype=TEXT_PLAIN)
156 #Set status and reason
157 #/status?policyid=<policyid>&status=<status>[&reason=<reason>]
158 @app.route('/status', methods=['PUT'])
161 policy_id=request.args.get('policyid')
162 if (policy_id is None):
163 return Response('Parameter <policyid> missing in request', status=400, mimetype=TEXT_PLAIN)
164 if policy_id not in policy_status.keys():
165 return Response('Policyid: '+policy_id+' not found.', status=404, mimetype=TEXT_PLAIN)
166 status=request.args.get('status')
168 return Response('Parameter <status> missing in request', status=400, mimetype=TEXT_PLAIN)
169 reason=request.args.get('reason')
171 ps["enforceStatus"] = status
172 msg="Status set to "+status
173 if (reason is not None):
174 ps["enforceReason"] = reason
175 msg=msg+" and "+reason
176 policy_status[policy_id] = ps
177 msg=msg+" for policy: " + policy_id
178 return Response(msg, 200, mimetype=TEXT_PLAIN)
181 #/status?policyid=<policyid>
182 @app.route('/sendstatus', methods=['POST'])
184 policyid=request.args.get('policyid')
185 if (policyid is None):
186 return Response('Parameter <policyid> missing in request', status=400, mimetype=TEXT_PLAIN)
188 if (policyid not in policy_status.keys()):
189 return Response('Policyid: '+policyid+' not found.', status=404, mimetype=TEXT_PLAIN)
191 ps=policy_status[policyid]
192 cb=callbacks[policyid]
194 resp=requests.post(cb,json=json.dumps(ps), verify=False) # NOSONAR
196 return Response('Post status failed, could not send to: '+str(cb), status=500, mimetype=TEXT_PLAIN)
197 if (resp.status_code<199 & resp.status_code > 299):
198 return Response('Post status failed with code: '+resp.status_code, status=500, mimetype=TEXT_PLAIN)
201 return Response(data, 200, mimetype='application/json')
203 #Receive status (only for testing callbacks)
205 @app.route('/statustest', methods=['POST', 'PUT'])
209 data = json.loads(data)
211 return Response("The status data is corrupt or missing.", 400, mimetype=TEXT_PLAIN)
213 return Response(json.dumps(data), 200, mimetype='application/json')
215 #Receive a data delivery package
217 @app.route('/datadelivery', methods=['POST'])
219 global data_delivery_counter
222 data = json.loads(data)
224 return Response("The data is corrupt or missing.", 400, mimetype=TEXT_PLAIN)
225 data_delivery_counter += 1
226 return Response("", 200, mimetype=TEXT_PLAIN)
230 @app.route('/counter/<string:countername>', methods=['GET'])
231 def getcounter(countername):
233 if (countername == "num_instances"):
234 return Response(str(len(policy_fingerprint)), 200, mimetype=TEXT_PLAIN)
235 elif (countername == "num_types"):
236 return Response(str(len(policy_instances)),200, mimetype=TEXT_PLAIN)
237 elif (countername == "interface"):
240 return Response(str(pp[len(pp)-1]),200, mimetype=TEXT_PLAIN)
241 elif (countername == "remote_hosts"):
242 hosts=",".join(hosts_set)
243 return str(hosts),200
244 elif (countername == "datadelivery"):
245 return Response(str(data_delivery_counter),200, mimetype=TEXT_PLAIN)
247 return Response("Counter name: "+countername+" not found.",404, mimetype=TEXT_PLAIN)
250 if len(sys.argv) >= 2:
251 if isinstance(sys.argv[1], int):
252 port_number = sys.argv[1]
254 app.add_api('ORAN_A1-p_V2.0.0_api.yaml')
256 if __name__ == '__main__':
257 app.run(port=port_number, host="127.0.0.1", threaded=False)