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