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