Towards a1 1.0.0: rmr improvements
[ric-plt/a1.git] / a1 / controller.py
1 """
2 Main a1 controller
3 """
4 # ==================================================================================
5 #       Copyright (c) 2019 Nokia
6 #       Copyright (c) 2018-2019 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 import json
21 from flask import Response
22 from jsonschema import validate
23 from jsonschema.exceptions import ValidationError
24 import connexion
25 from a1 import get_module_logger
26 from a1 import a1rmr, exceptions, data
27
28
29 logger = get_module_logger(__name__)
30
31
32 def _try_func_return(func):
33     """
34     generic caller that returns the apporp http response if exceptions are raised
35     """
36     try:
37         return func()
38     except (ValidationError, exceptions.PolicyTypeAlreadyExists) as exc:
39         logger.exception(exc)
40         return "", 400
41     except (exceptions.PolicyTypeNotFound, exceptions.PolicyInstanceNotFound) as exc:
42         logger.exception(exc)
43         return "", 404
44     except BaseException as exc:
45         # catch all, should never happen...
46         logger.exception(exc)
47         return Response(status=500)
48
49
50 def _gen_body_to_handler(operation, policy_type_id, policy_instance_id, payload=None):
51     """
52     used to create the payloads that get sent to downstream policy handlers
53     """
54     return {
55         "operation": operation,
56         "policy_type_id": policy_type_id,
57         "policy_instance_id": policy_instance_id,
58         "payload": payload,
59     }
60
61
62 # Healthcheck
63
64
65 def get_healthcheck():
66     """
67     Handles healthcheck GET
68     Currently, this basically checks the server is alive.a1rmr
69     """
70     return "", 200
71
72
73 # Policy types
74
75
76 def get_all_policy_types():
77     """
78     Handles GET /a1-p/policytypes
79     """
80     return _try_func_return(data.get_type_list)
81
82
83 def create_policy_type(policy_type_id):
84     """
85     Handles PUT /a1-p/policytypes/policy_type_id
86     """
87
88     def put_type_handler():
89         data.store_policy_type(policy_type_id, body)
90         return "", 201
91
92     body = connexion.request.json
93     return _try_func_return(put_type_handler)
94
95
96 def get_policy_type(policy_type_id):
97     """
98     Handles GET /a1-p/policytypes/policy_type_id
99     """
100     return _try_func_return(lambda: data.get_policy_type(policy_type_id))
101
102
103 def delete_policy_type(policy_type_id):
104     """
105     Handles DELETE /a1-p/policytypes/policy_type_id
106     """
107     logger.error(policy_type_id)
108     return "", 501
109
110
111 # Policy instances
112
113
114 def get_all_instances_for_type(policy_type_id):
115     """
116     Handles GET /a1-p/policytypes/policy_type_id/policies
117     """
118
119     def get_all_instance_handler():
120         # try to clean up instances for this type
121         for policy_instance_id in data.get_instance_list(policy_type_id):
122             data.delete_policy_instance_if_applicable(policy_type_id, policy_instance_id)
123
124         # re-fetch this list as it may have changed
125         return data.get_instance_list(policy_type_id), 200
126
127     return _try_func_return(get_all_instance_handler)
128
129
130 def get_policy_instance(policy_type_id, policy_instance_id):
131     """
132     Handles GET /a1-p/policytypes/polidyid/policies/policy_instance_id
133     """
134
135     def get_instance_handler():
136         # delete if applicable (will raise if not applicable to begin with)
137         data.delete_policy_instance_if_applicable(policy_type_id, policy_instance_id)
138
139         # raise 404 now that we may have deleted, or get the instance otherwise
140         return data.get_policy_instance(policy_type_id, policy_instance_id), 200
141
142     return _try_func_return(get_instance_handler)
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     def get_status_handler():
156         # delete if applicable (will raise if not applicable to begin with)
157         data.delete_policy_instance_if_applicable(policy_type_id, policy_instance_id)
158
159         vector = data.get_policy_instance_statuses(policy_type_id, policy_instance_id)
160         for i in vector:
161             if i == "OK":
162                 return "IN EFFECT", 200
163         return "NOT IN EFFECT", 200
164
165     return _try_func_return(get_status_handler)
166
167
168 def create_or_replace_policy_instance(policy_type_id, policy_instance_id):
169     """
170     Handles PUT /a1-p/policytypes/polidyid/policies/policy_instance_id
171     """
172     instance = connexion.request.json
173
174     def put_instance_handler():
175         """
176         Handles policy instance put
177
178         For now, policy_type_id is used as the message type
179         """
180         #  validate the PUT against the schema
181         schema = data.get_policy_type(policy_type_id)["create_schema"]
182         validate(instance=instance, schema=schema)
183
184         # store the instance
185         data.store_policy_instance(policy_type_id, policy_instance_id, instance)
186
187         # send rmr (best effort)
188         body = _gen_body_to_handler("CREATE", policy_type_id, policy_instance_id, payload=instance)
189         a1rmr.send(json.dumps(body), message_type=policy_type_id)
190
191         return "", 202
192
193     return _try_func_return(put_instance_handler)
194
195
196 def delete_policy_instance(policy_type_id, policy_instance_id):
197     """
198     Handles DELETE /a1-p/policytypes/polidyid/policies/policy_instance_id
199     """
200
201     def delete_instance_handler():
202         """
203         here we send out the DELETEs but we don't delete the instance until a GET is called where we check the statuses
204         """
205         # send rmr (best effort)
206         body = _gen_body_to_handler("DELETE", policy_type_id, policy_instance_id)
207         a1rmr.send(json.dumps(body), message_type=policy_type_id)
208
209         return "", 202
210
211     return _try_func_return(delete_instance_handler)