5daa8a56ff640b4d939315f04107817a1bd9cd44
[ric-plt/a1.git] / a1 / controller.py
1 """
2 Main a1 controller
3 """
4 # ==================================================================================
5 #       Copyright (c) 2019-2020 Nokia
6 #       Copyright (c) 2018-2020 AT&T Intellectual Property.
7 #
8 #   Licensed under the Apache License, Version 2.0 (the "License");
9 #   you may not use this file except in compliance with the License.
10 #   You may obtain a copy of the License at
11 #
12 #          http://www.apache.org/licenses/LICENSE-2.0
13 #
14 #   Unless required by applicable law or agreed to in writing, software
15 #   distributed under the License is distributed on an "AS IS" BASIS,
16 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 #   See the License for the specific language governing permissions and
18 #   limitations under the License.
19 # ==================================================================================
20 from jsonschema import validate
21 from jsonschema.exceptions import ValidationError
22 import connexion
23 from mdclogpy import Logger
24 from ricsdl.exceptions import RejectedByBackend, NotConnected, BackendError
25 from a1 import a1rmr, exceptions, data
26
27
28 mdc_logger = Logger(name=__name__)
29
30
31 def _try_func_return(func):
32     """
33     helper method that runs the function and returns a detailed http response if an exception is raised.
34     """
35     try:
36         return func()
37     except (ValidationError, exceptions.PolicyTypeAlreadyExists, exceptions.CantDeleteNonEmptyType) as exc:
38         msg = repr(exc)
39         mdc_logger.warning("Request failed, returning 400: {0}".format(msg))
40         return msg, 400
41     except (exceptions.PolicyTypeNotFound, exceptions.PolicyInstanceNotFound) as exc:
42         msg = repr(exc)
43         mdc_logger.warning("Request failed, returning 404: {0}".format(msg))
44         return msg, 404
45     except (RejectedByBackend, NotConnected, BackendError) as exc:
46         """
47         These are SDL errors. At the time of development here, we do not have a good understanding
48         which of these errors are "try again later it may work" and which are "never going to work".
49         There is some discussion that RejectedByBackend is in the latter category, suggesting it
50         should map to 400, but until we understand the root cause of these errors, it's confusing
51         to clients to give them a 400 (a "your fault" code) because they won't know how to fix.
52         For now, we log, and 503, and investigate the logs later to improve the handling/reporting.
53         """
54         # mdc_logger.exception(exc)  # waiting for https://jira.o-ran-sc.org/browse/RIC-39
55         msg = repr(exc)
56         mdc_logger.warning("Request failed, returning 503: {0}".format(msg))
57         return msg, 503
58
59     # let other types of unexpected exceptions blow up and log
60
61
62 # Healthcheck
63
64
65 def get_healthcheck():
66     """
67     Handles healthcheck GET
68     Currently, this checks:
69     1. whether the a1 webserver is up (if it isn't, this won't even be called, so even entering this function confirms it is)
70     2. checks whether the rmr thread is running and has completed a loop recently
71     3. checks that our SDL connection is healthy
72     """
73     if not a1rmr.healthcheck_rmr_thread():
74         mdc_logger.debug("A1 is not healthy due to the rmr thread")
75         return "rmr thread is unhealthy", 500
76     if not data.SDL.healthcheck():
77         mdc_logger.debug("A1 is not healthy because it does not have a connection to SDL")
78         return "sdl connection is unhealthy", 500
79     return "", 200
80
81
82 # Policy types
83
84
85 def get_all_policy_types():
86     """
87     Handles GET /a1-p/policytypes
88     """
89     return _try_func_return(data.get_type_list)
90
91
92 def create_policy_type(policy_type_id):
93     """
94     Handles PUT /a1-p/policytypes/policy_type_id
95     """
96
97     def put_type_handler():
98         data.store_policy_type(policy_type_id, body)
99         mdc_logger.debug("Policy type {} created.".format(policy_type_id))
100         return "", 201
101
102     body = connexion.request.json
103     return _try_func_return(put_type_handler)
104
105
106 def get_policy_type(policy_type_id):
107     """
108     Handles GET /a1-p/policytypes/policy_type_id
109     """
110     return _try_func_return(lambda: data.get_policy_type(policy_type_id))
111
112
113 def delete_policy_type(policy_type_id):
114     """
115     Handles DELETE /a1-p/policytypes/policy_type_id
116     """
117
118     def delete_policy_type_handler():
119         data.delete_policy_type(policy_type_id)
120         mdc_logger.debug("Policy type {} deleted.".format(policy_type_id))
121         return "", 204
122
123     return _try_func_return(delete_policy_type_handler)
124
125
126 # Policy instances
127
128
129 def get_all_instances_for_type(policy_type_id):
130     """
131     Handles GET /a1-p/policytypes/policy_type_id/policies
132     """
133     return _try_func_return(lambda: data.get_instance_list(policy_type_id))
134
135
136 def get_policy_instance(policy_type_id, policy_instance_id):
137     """
138     Handles GET /a1-p/policytypes/polidyid/policies/policy_instance_id
139     """
140     return _try_func_return(lambda: data.get_policy_instance(policy_type_id, policy_instance_id))
141
142
143 def get_policy_instance_status(policy_type_id, policy_instance_id):
144     """
145     Handles GET /a1-p/policytypes/polidyid/policies/policy_instance_id/status
146
147     Return the aggregated status. The order of rules is as follows:
148         1. If a1 has received at least one status, and *all* received statuses are "DELETED", we blow away the instance and return a 404
149         2. if a1 has received at least one status and at least one is OK, we return "IN EFFECT"
150         3. "NOT IN EFFECT" otherwise (no statuses, or none are OK but not all are deleted)
151     """
152
153     return _try_func_return(lambda: data.get_policy_instance_status(policy_type_id, policy_instance_id))
154
155
156 def create_or_replace_policy_instance(policy_type_id, policy_instance_id):
157     """
158     Handles PUT /a1-p/policytypes/polidyid/policies/policy_instance_id
159     """
160     instance = connexion.request.json
161
162     def put_instance_handler():
163         """
164         Handles policy instance put
165
166         For now, policy_type_id is used as the message type
167         """
168         #  validate the PUT against the schema
169         schema = data.get_policy_type(policy_type_id)["create_schema"]
170         validate(instance=instance, schema=schema)
171
172         # store the instance
173         data.store_policy_instance(policy_type_id, policy_instance_id, instance)
174
175         # queue rmr send (best effort)
176         a1rmr.queue_instance_send(("CREATE", policy_type_id, policy_instance_id, instance))
177
178         return "", 202
179
180     return _try_func_return(put_instance_handler)
181
182
183 def delete_policy_instance(policy_type_id, policy_instance_id):
184     """
185     Handles DELETE /a1-p/policytypes/polidyid/policies/policy_instance_id
186     """
187
188     def delete_instance_handler():
189         data.delete_policy_instance(policy_type_id, policy_instance_id)
190
191         # queue rmr send (best effort)
192         a1rmr.queue_instance_send(("DELETE", policy_type_id, policy_instance_id, ""))
193
194         return "", 202
195
196     return _try_func_return(delete_instance_handler)