First commit of the near-rt-ric simulator
[sim/a1-interface.git] / near-rt-ric-simulator / scripts / main.py
1 #!/usr/bin/python3
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
19 import connexion
20 import fileinput
21 import json
22 import sys
23
24 from flask import Flask, escape, request, make_response
25 from jsonschema import validate
26 from var_declaration import policy_instances, policy_types, policy_status, policy_type_per_instance
27
28 app = connexion.App(__name__, specification_dir='.')
29
30 @app.route('/policytypes/<string:policyTypeId>', methods=['PUT','DELETE'])
31 def policy_type(policyTypeId):
32   if request.method == 'PUT':
33     data = request.data.decode("utf-8")
34     data = data.replace("'", "\"")
35     data = json.loads(data)
36     policy_types[policyTypeId] = data
37     return ('The policy type was either created or updated for policy type id: ' + policyTypeId)
38   elif request.method == 'DELETE':
39     if policyTypeId in policy_types.keys():
40       policy_types.pop(policyTypeId)
41       return make_response("policy type successfully deleted for policy type id: " + policyTypeId, 200)
42     else:
43       return make_response("No policy type defined for the specified id", 404)
44
45 @app.route('/', methods=['GET'])
46 def test():
47     return("Everything is fine", 200)
48
49 @app.route('/deleteinstances', methods=['DELETE'])
50 def delete_instances():
51   global policy_instances
52   global policy_status
53   global policy_type_per_instance
54   policy_instances.clear()
55   policy_status.clear()
56   policy_type_per_instance.clear()
57   return("All policy instances deleted", 200)
58
59 @app.route('/deletetypes', methods=['DELETE'])
60 def delete_types():
61   global policy_types
62   policy_types.clear()
63   return("All policy types deleted", 200)
64
65 @app.route('/<string:policyId>/<string:enforceStatus>', methods=['PUT'])
66 def set_status(policyId, enforceStatus):
67   if policyId in policy_instances.keys():
68     if policy_type_per_instance[policyId] == "UNDEFINED":
69       ps = {}
70       ps["policyId"] = policyId
71       ps["enforceStatus"] = enforceStatus
72     else:
73       policy_type_id = policy_type_per_instance[policyId]
74       status_schema = policy_types[policy_type_id]["statusSchema"]
75       ps = {}
76       ps["policyId"] = policyId
77       ps["enforceStatus"] = enforceStatus
78       try:
79         validate(instance=ps, schema=status_schema)
80       except:
81         return(set_error(None, "The json does not validate against the status schema.", 400, None, None, None, None, None))
82   policy_status.pop(policyId)
83   policy_status[policyId] = ps
84   return("Status updated for policy: " + policyId, 200)
85
86 @app.route('/<string:policyId>/<string:enforceStatus>/<string:enforceReason>', methods=['PUT'])
87 def set_status_with_reason(policyId, enforceStatus, enforceReason):
88   if policyId in policy_instances.keys():
89     if policy_type_per_instance[policyId] == "UNDEFINED":
90       ps = {}
91       ps["policyId"] = policyId
92       ps["enforceStatus"] = enforceStatus
93       ps["enforceReason"] = enforceReason
94     else:
95       policy_type_id = policy_type_per_instance[policyId]
96       status_schema = policy_types[policy_type_id]["statusSchema"]
97       ps = {}
98       ps["policyId"] = policyId
99       ps["enforceStatus"] = enforceStatus
100       ps["enforceReason"] = enforceReason
101       try:
102         validate(instance=ps, schema=status_schema)
103       except:
104         return(set_error(None, "The json does not validate against the status schema.", 400, None, None, None, None, None))
105   policy_status.pop(policyId)
106   policy_status[policyId] = ps
107   return("Status updated for policy: " + policyId, 200)
108
109 #Metrics function
110
111 @app.route('/counter/<string:countername>', methods=['GET'])
112 def getCounter(countername):
113     if (countername == "num_instances"):
114         return str(len(policy_instances)),200
115     elif (countername == "num_types"):
116         return str(len(policy_types)),200
117     else:
118         return "Counter name: "+countername+" not found.",404
119
120
121 port_number = 8085
122 if len(sys.argv) >= 2:
123   if isinstance(sys.argv[1], int):
124     port_number = sys.argv[1]
125
126 app.add_api('../a1-openapi.yaml')
127 app.run(port=port_number)
128