3bc8cbe8d7adf0c31bf90032d5c08a4ce62f615e
[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
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 deleteinstances():
50
51   for i in policy_instances.keys():
52     policy_instances[i]={}
53
54   policy_status.clear()
55   forced_settings.clear()
56   forced_settings['code']=None
57   forced_settings['delay']=None
58   policy_fingerprint.clear()
59   return Response("All policy instances deleted", 200, mimetype='text/plain')
60
61 #Delete all - all reset
62 @app.route('/deleteall', methods=['POST'])
63 def deleteall():
64
65   policy_instances.clear()
66   policy_types.clear()
67   policy_status.clear()
68   forced_settings['code']=None
69   forced_settings['delay']=None
70   policy_fingerprint.clear()
71   return Response("All policy instances and types deleted", 200, mimetype='text/plain')
72
73 #Load a policy type
74 @app.route('/policytype', methods=['PUT'])
75 def policytype():
76
77   policyTypeId=request.args.get('id')
78   if (policyTypeId is None):
79     return Response('Parameter <id> missing in request', status=400, mimetype='text/plain')
80   try:
81     val=int(policyTypeId)
82   except:
83     return Response("The policy type id is not an int", 400, mimetype='text/plain')
84   try:
85     data = request.data
86     data = json.loads(data)
87   except:
88     return Response("The policy type is corrupt or missing", 400, mimetype='text/plain')
89
90   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()):
91     return Response("The policy type missing atributes", 400, mimetype='text/plain')
92
93   retcode=201
94   if (policyTypeId in policy_types.keys()):
95     retcode=200
96     if (len(policy_instances[policyTypeId]) > 0):
97       return Response("The policy type already exists and instances exists", 400, mimetype='text/plain')
98
99   policy_types[policyTypeId]=data
100   policy_instances[policyTypeId]={}
101   return Response("Policy type " + policyTypeId + " is OK.", retcode, mimetype='text/plain')
102
103 #Delete a policy type
104 @app.route('/policytype', methods=['DELETE'])
105 def del_policytype():
106
107   policyTypeId=request.args.get('id')
108   if (policyTypeId is None):
109     return Response('Parameter <id> missing in request', status=400, mimetype='text/plain')
110   try:
111     val=int(policyTypeId)
112   except:
113     return Response("The policy type id is not an int", 400, mimetype='text/plain')
114
115   if (policyTypeId in policy_types.keys()):
116     if (len(policy_instances[policyTypeId]) > 0):
117       return Response("The policy type already exists and instances exists", 400, mimetype='text/plain')
118
119     del policy_types[policyTypeId]
120     del policy_instances[policyTypeId]
121     return Response("Policy type " + policyTypeId + " is OK.", 204, mimetype='text/plain')
122
123   return Response("Policy type " + policyTypeId + " not found.", 204, mimetype='text/plain')
124
125
126 # Get all policy type ids
127 @app.route('/policytypes', methods=['GET'])
128 def get_policytype_ids():
129
130   return (json.dumps(list(policy_instances.keys())), 200)
131
132 #Set force response for one A1 response
133 #/forceresponse?code=<responsecode>
134 @app.route('/forceresponse', methods=['POST'])
135 def forceresponse():
136
137   try:
138     forced_settings['code']=int(request.args.get('code'))
139   except:
140     forced_settings['code']=None
141   return Response("Force response code: " + str(forced_settings['code']) + " set for one single A1 response", 200, mimetype='text/plain')
142
143 #Set force delay response, in seconds, for all A1 responses
144 #/froceesponse?delay=<seconds>
145 @app.route('/forcedelay', methods=['POST'])
146 def forcedelay():
147
148   try:
149     forced_settings['delay']=int(request.args.get('delay'))
150   except:
151     forced_settings['delay']=None
152   return Response("Force delay: " + str(forced_settings['delay']) + " sec set for all A1 responses", 200, mimetype='text/plain')
153
154
155 #Set status and reason
156 #/status?policyid=<policyid>&status=<status>[&deleted=<boolean>][&created_at=<timestamp>]
157 @app.route('/status', methods=['PUT'])
158 def setstatus():
159
160   policyId=request.args.get('policyid')
161   if (policyId is None):
162     return Response('Parameter <policyid> missing in request', status=400, mimetype='text/plain')
163
164   if policyId not in policy_status.keys():
165     return Response('Policyid: '+policyId+' not found.', status=404, mimetype='text/plain')
166   status=request.args.get('status')
167   if (status is None):
168     return Response('Parameter <status> missing in request', status=400, mimetype='text/plain')
169   policy_status[policyId]["instance_status"]=status
170   msg = "Status set to "+status
171   deleted_policy=request.args.get('deleted')
172   if (deleted_policy is not None):
173     policy_status[policyId]["has_been_deleted"]=deleted_policy
174     msg = msg + " and has_been_deleted set to "+deleted_policy
175   created_at = request.args.get('created_at')
176   if (created_at is not None):
177     policy_status[policyId]["created_at"]=created_at
178     msg = msg + " and created_at set to "+created_at
179   msg=msg + " for policy: " + policyId
180   return Response(msg, 200, mimetype='text/plain')
181
182
183 #Metrics function
184 #Get a named counter
185 @app.route('/counter/<string:countername>', methods=['GET'])
186 def getCounter(countername):
187
188   if (countername == "num_instances"):
189     return Response(str(len(policy_fingerprint)), 200, mimetype='text/plain')
190   elif (countername == "num_types"):
191     return Response(str(len(policy_instances)),200, mimetype='text/plain')
192   elif (countername == "interface"):
193     p=Path(os.getcwd())
194     pp=p.parts
195     return Response(str(pp[len(pp)-1]),200, mimetype='text/plain')
196   else:
197     return Response("Counter name: "+countername+" not found.",404, mimetype='text/plain')
198
199 port_number = 8085
200 if len(sys.argv) >= 2:
201   if isinstance(sys.argv[1], int):
202     port_number = sys.argv[1]
203
204 app.add_api('openapi.yaml')
205 app.run(port=port_number)
206