83aaf4a71548d78cf4abe522780bd9c88f282bbe
[sim/a1-interface.git] / near-rt-ric-simulator / src / STD_1.1.3 / main.py
1 #  ============LICENSE_START===============================================
2 #  Copyright (C) 2020 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
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
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=================================================
16 #
17
18 import connexion
19 import json
20 import sys
21 import os
22 import requests
23
24 from pathlib import Path
25 from flask import Flask, escape, request, Response
26 from jsonschema import validate
27 from var_declaration import policy_instances, policy_status, callbacks, forced_settings, policy_fingerprint
28 from maincommon import *
29
30
31 check_apipath()
32
33 app = connexion.App(__name__, specification_dir=apipath)
34
35 #Check alive function
36 @app.route('/', methods=['GET'])
37 def test():
38
39   return Response("OK", 200, mimetype='text/plain')
40
41 #Return the current and all supported yamls for the this container
42 @app.route('/container_interfaces', methods=['GET'])
43 def container_interfaces():
44
45     return get_supported_interfaces_response()
46
47 #Delete all created instances and status
48 @app.route('/deleteinstances', methods=['POST'])
49 def delete_instances():
50
51   policy_instances.clear()
52   policy_status.clear()
53   callbacks.clear()
54   forced_settings['code']=None
55   forced_settings['delay']=None
56   policy_fingerprint.clear()
57   return Response("All policy instances deleted", 200, mimetype='text/plain')
58
59 #Delete all - all reset
60 #(same as delete_instances but kept to in order to use the same interface as other version of the simulator)
61 @app.route('/deleteall', methods=['POST'])
62 def delete_all():
63   return delete_instances()
64
65 #Set force response for one A1 response
66 #/forceresponse?code=<responsecode>
67 @app.route('/forceresponse', methods=['POST'])
68 def forceresponse():
69
70   try:
71     forced_settings['code']=request.args.get('code')
72   except:
73     forced_settings['code']=None
74   return Response("Force response code: " + str(forced_settings['code']) + " set for one single A1 response", 200, mimetype='text/plain')
75
76 #Set force delay response, in seconds, for all A1 responses
77 #/froceesponse?delay=<seconds>
78 @app.route('/forcedelay', methods=['POST'])
79 def forcedelay():
80
81   try:
82     forced_settings['delay']=request.args.get('delay')
83   except:
84     forced_settings['delay']=None
85   return Response("Force delay: " + str(forced_settings['delay']) + " sec set for all A1 responses", 200, mimetype='text/plain')
86
87
88 #Set status and reason
89 #/status?policyid=<policyid>&status=<status>[&reason=<reason>]
90 @app.route('/status', methods=['PUT'])
91 def setstatus():
92
93   policyId=request.args.get('policyid')
94   if (policyId is None):
95     return Response('Parameter <policyid> missing in request', status=400, mimetype='text/plain')
96   if policyId not in policy_instances.keys():
97     return Response('Policyid: '+policyId+' not found.', status=404, mimetype='text/plain')
98   status=request.args.get('status')
99   if (status is None):
100     return Response('Parameter <status> missing in request', status=400, mimetype='text/plain')
101   reason=request.args.get('reason')
102   ps = {}
103   ps["enforceStatus"] = status
104   msg="Status set to "+status
105   if (reason is not None):
106     ps["enforceReason"] = reason
107     msg=msg+" and "+reason
108   policy_status[policyId] = ps
109   msg=msg+" for policy: " + policyId
110   return Response(msg, 200, mimetype='text/plain')
111
112 #Send status
113 #/status?policyid=<policyid>
114 @app.route('/sendstatus', methods=['POST'])
115 def sendstatus():
116   policyid=request.args.get('policyid')
117   if (policyid is None):
118     return Response('Parameter <policyid> missing in request', status=400, mimetype='text/plain')
119
120   if (policyid not in policy_status.keys()):
121     return Response('Policyid: '+policyid+' not found.', status=404, mimetype='text/plain')
122
123   ps=policy_status[policyid]
124   cb=callbacks[policyid]
125   try:
126     resp=requests.post(cb,json=json.dumps(ps))
127   except:
128     return Response('Post status failed, could not send to: '+str(cb), status=500, mimetype='text/plain')
129   if (resp.status_code<199 & resp.status_code > 299):
130     return Response('Post status failed with code: '+resp.status_code, status=500, mimetype='text/plain')
131
132   data = resp.json()
133   return Response(data, 200, mimetype='application/json')
134
135 #Receive status (only for testing callbacks)
136 #/statustest
137 @app.route('/statustest', methods=['POST', 'PUT'])
138 def statustest():
139   try:
140     data = request.data
141     data = json.loads(data)
142   except:
143     return Response("The status data is corrupt or missing.", 400, mimetype='text/plain')
144
145   return Response(json.dumps(data), 200, mimetype='application/json')
146
147 #Metrics function
148 #Get a named counter
149 @app.route('/counter/<string:countername>', methods=['GET'])
150 def getCounter(countername):
151
152   if (countername == "num_instances"):
153     return Response(str(len(policy_instances)), 200, mimetype='text/plain')
154   elif (countername == "num_types"):
155     return Response("0",200, mimetype='text/plain')
156   elif (countername == "interface"):
157     p=Path(os.getcwd())
158     pp=p.parts
159     return Response(str(pp[len(pp)-1]),200, mimetype='text/plain')
160   else:
161     return Response("Counter name: "+countername+" not found.",404, mimetype='text/plain')
162
163 port_number = 8085
164 if len(sys.argv) >= 2:
165   if isinstance(sys.argv[1], int):
166     port_number = sys.argv[1]
167
168 app.add_api('STD_A1.yaml')
169 app.run(port=port_number)