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