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