Update a1-interface with nginx to support https
[sim/a1-interface.git] / near-rt-ric-simulator / src / OSC_2.1.0 / 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_types, policy_status, policy_fingerprint, forced_settings, hosts_set
28 from maincommon import *
29 from time import sleep
30
31
32 check_apipath()
33
34 app = connexion.FlaskApp(__name__, specification_dir=apipath)
35 t=[] ##varialbe for test purpose
36
37 #long poll
38 @app.route('/long', methods=['GET'])
39 def longpoll():
40     global t
41     sleep(10)
42     t.append(1)
43     return Response(str(t), 200, mimetype='text/plain')
44
45 #short poll
46 @app.route('/short', methods=['GET'])
47 def shortpoll():
48     global t
49     t.append(2)
50     return Response(str(t), 200, mimetype='text/plain')
51
52 #Check alive function
53 @app.route('/', methods=['GET'])
54 def test():
55
56     return Response("OK", 200, mimetype='text/plain')
57
58 #Return the current and all supported yamls for the this container
59 @app.route('/container_interfaces', methods=['GET'])
60 def container_interfaces():
61
62     return get_supported_interfaces_response()
63
64 #Delete all created instances and status
65 @app.route('/deleteinstances', methods=['POST'])
66 def deleteinstances():
67
68   for i in policy_instances.keys():
69     policy_instances[i]={}
70
71   policy_status.clear()
72   forced_settings.clear()
73   forced_settings['code']=None
74   forced_settings['delay']=None
75   policy_fingerprint.clear()
76   return Response("All policy instances deleted", 200, mimetype='text/plain')
77
78 #Delete all - all reset
79 @app.route('/deleteall', methods=['POST'])
80 def deleteall():
81
82   policy_instances.clear()
83   policy_types.clear()
84   policy_status.clear()
85   forced_settings['code']=None
86   forced_settings['delay']=None
87   policy_fingerprint.clear()
88   return Response("All policy instances and types deleted", 200, mimetype='text/plain')
89
90 #Load a policy type
91 @app.route('/policytype', methods=['PUT'])
92 def policytype():
93
94   policyTypeId=request.args.get('id')
95   if (policyTypeId is None):
96     return Response('Parameter <id> missing in request', status=400, mimetype='text/plain')
97   try:
98     val=int(policyTypeId)
99   except:
100     return Response("The policy type id is not an int", 400, mimetype='text/plain')
101   try:
102     data = request.data
103     data = json.loads(data)
104   except:
105     return Response("The policy type is corrupt or missing", 400, mimetype='text/plain')
106
107   if ('name' not in data.keys() or 'description' not in data.keys() or 'policy_type_id' not in data.keys() or'create_schema' not in data.keys()):
108     return Response("The policy type missing atributes", 400, mimetype='text/plain')
109
110   retcode=201
111   if (policyTypeId in policy_types.keys()):
112     retcode=200
113     if (len(policy_instances[policyTypeId]) > 0):
114       return Response("The policy type already exists and instances exists", 400, mimetype='text/plain')
115
116   policy_types[policyTypeId]=data
117   policy_instances[policyTypeId]={}
118   return Response("Policy type " + policyTypeId + " is OK.", retcode, mimetype='text/plain')
119
120 #Delete a policy type
121 @app.route('/policytype', methods=['DELETE'])
122 def del_policytype():
123
124   policyTypeId=request.args.get('id')
125   if (policyTypeId is None):
126     return Response('Parameter <id> missing in request', status=400, mimetype='text/plain')
127   try:
128     val=int(policyTypeId)
129   except:
130     return Response("The policy type id is not an int", 400, mimetype='text/plain')
131
132   if (policyTypeId in policy_types.keys()):
133     if (len(policy_instances[policyTypeId]) > 0):
134       return Response("The policy type already exists and instances exists", 400, mimetype='text/plain')
135
136     del policy_types[policyTypeId]
137     del policy_instances[policyTypeId]
138     return Response("Policy type " + policyTypeId + " is OK.", 204, mimetype='text/plain')
139
140   return Response("Policy type " + policyTypeId + " not found.", 204, mimetype='text/plain')
141
142
143 # Get all policy type ids
144 @app.route('/policytypes', methods=['GET'])
145 def get_policytype_ids():
146
147   return (json.dumps(list(policy_instances.keys())), 200)
148
149 #Set force response for one A1 response
150 #/forceresponse?code=<responsecode>
151 @app.route('/forceresponse', methods=['POST'])
152 def forceresponse():
153
154   try:
155     forced_settings['code']=int(request.args.get('code'))
156   except:
157     forced_settings['code']=None
158   return Response("Force response code: " + str(forced_settings['code']) + " set for one single A1 response", 200, mimetype='text/plain')
159
160 #Set force delay response, in seconds, for all A1 responses
161 #/froceesponse?delay=<seconds>
162 @app.route('/forcedelay', methods=['POST'])
163 def forcedelay():
164
165   try:
166     forced_settings['delay']=int(request.args.get('delay'))
167   except:
168     forced_settings['delay']=None
169   return Response("Force delay: " + str(forced_settings['delay']) + " sec set for all A1 responses", 200, mimetype='text/plain')
170
171
172 #Set status and reason
173 #/status?policyid=<policyid>&status=<status>[&deleted=<boolean>][&created_at=<timestamp>]
174 @app.route('/status', methods=['PUT'])
175 def setstatus():
176
177   policyId=request.args.get('policyid')
178   if (policyId is None):
179     return Response('Parameter <policyid> missing in request', status=400, mimetype='text/plain')
180
181   if policyId not in policy_status.keys():
182     return Response('Policyid: '+policyId+' not found.', status=404, mimetype='text/plain')
183   status=request.args.get('status')
184   if (status is None):
185     return Response('Parameter <status> missing in request', status=400, mimetype='text/plain')
186   policy_status[policyId]["instance_status"]=status
187   msg = "Status set to "+status
188   deleted_policy=request.args.get('deleted')
189   if (deleted_policy is not None):
190     policy_status[policyId]["has_been_deleted"]=deleted_policy
191     msg = msg + " and has_been_deleted set to "+deleted_policy
192   created_at = request.args.get('created_at')
193   if (created_at is not None):
194     policy_status[policyId]["created_at"]=created_at
195     msg = msg + " and created_at set to "+created_at
196   msg=msg + " for policy: " + policyId
197   return Response(msg, 200, mimetype='text/plain')
198
199
200 #Metrics function
201 #Get a named counter
202 @app.route('/counter/<string:countername>', methods=['GET'])
203 def getCounter(countername):
204
205   if (countername == "num_instances"):
206     return Response(str(len(policy_fingerprint)), 200, mimetype='text/plain')
207   elif (countername == "num_types"):
208     return Response(str(len(policy_instances)),200, mimetype='text/plain')
209   elif (countername == "interface"):
210     p=Path(os.getcwd())
211     pp=p.parts
212     return Response(str(pp[len(pp)-1]),200, mimetype='text/plain')
213   elif (countername == "remote_hosts"):
214     hosts=",".join(hosts_set)
215     return str(hosts),200
216   else:
217     return Response("Counter name: "+countername+" not found.",404, mimetype='text/plain')
218
219 port_number = 2222
220 if len(sys.argv) >= 2:
221   if isinstance(sys.argv[1], int):
222     port_number = sys.argv[1]
223
224 app.add_api('openapi.yaml')
225
226 app.run(port=port_number, host="127.0.0.1", threaded=False)