b3ce88edb6e19c094b386e49301f5c7678c4f00b
[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, exceptions.CantDeleteNonEmptyType):
39         return "", 400
40     except (exceptions.PolicyTypeNotFound, exceptions.PolicyInstanceNotFound):
41         return "", 404
42     except BaseException as exc:
43         # catch all, should never happen...
44         logger.exception(exc)
45         return Response(status=500)
46
47
48 def _gen_body_to_handler(operation, policy_type_id, policy_instance_id, payload=None):
49     """
50     used to create the payloads that get sent to downstream policy handlers
51     """
52     return {
53         "operation": operation,
54         "policy_type_id": policy_type_id,
55         "policy_instance_id": policy_instance_id,
56         "payload": payload,
57     }
58
59
60 # Healthcheck
61
62
63 def get_healthcheck():
64     """
65     Handles healthcheck GET
66     Currently, this basically checks the server is alive
67     """
68     return "", 200
69
70
71 # Policy types
72
73
74 def get_all_policy_types():
75     """
76     Handles GET /a1-p/policytypes
77     """
78     return _try_func_return(data.get_type_list)
79
80
81 def create_policy_type(policy_type_id):
82     """
83     Handles PUT /a1-p/policytypes/policy_type_id
84     """
85
86     def put_type_handler():
87         data.store_policy_type(policy_type_id, body)
88         return "", 201
89
90     body = connexion.request.json
91     return _try_func_return(put_type_handler)
92
93
94 def get_policy_type(policy_type_id):
95     """
96     Handles GET /a1-p/policytypes/policy_type_id
97     """
98     return _try_func_return(lambda: data.get_policy_type(policy_type_id))
99
100
101 def delete_policy_type(policy_type_id):
102     """
103     Handles DELETE /a1-p/policytypes/policy_type_id
104     """
105
106     def delete_policy_type_handler():
107         data.delete_policy_type(policy_type_id)
108         return "", 204
109
110     return _try_func_return(delete_policy_type_handler)
111
112
113 # Policy instances
114
115
116 def get_all_instances_for_type(policy_type_id):
117     """
118     Handles GET /a1-p/policytypes/policy_type_id/policies
119     """
120     return _try_func_return(lambda: data.get_instance_list(policy_type_id))
121
122
123 def get_policy_instance(policy_type_id, policy_instance_id):
124     """
125     Handles GET /a1-p/policytypes/polidyid/policies/policy_instance_id
126     """
127     return _try_func_return(lambda: data.get_policy_instance(policy_type_id, policy_instance_id))
128
129
130 def get_policy_instance_status(policy_type_id, policy_instance_id):
131     """
132     Handles GET /a1-p/policytypes/polidyid/policies/policy_instance_id/status
133
134     Return the aggregated status. The order of rules is as follows:
135         1. If a1 has received at least one status, and *all* received statuses are "DELETED", we blow away the instance and return a 404
136         2. if a1 has received at least one status and at least one is OK, we return "IN EFFECT"
137         3. "NOT IN EFFECT" otherwise (no statuses, or none are OK but not all are deleted)
138     """
139
140     def get_status_handler():
141         vector = data.get_policy_instance_statuses(policy_type_id, policy_instance_id)
142         for i in vector:
143             if i == "OK":
144                 return "IN EFFECT", 200
145         return "NOT IN EFFECT", 200
146
147     return _try_func_return(get_status_handler)
148
149
150 def create_or_replace_policy_instance(policy_type_id, policy_instance_id):
151     """
152     Handles PUT /a1-p/policytypes/polidyid/policies/policy_instance_id
153     """
154     instance = connexion.request.json
155
156     def put_instance_handler():
157         """
158         Handles policy instance put
159
160         For now, policy_type_id is used as the message type
161         """
162         #  validate the PUT against the schema
163         schema = data.get_policy_type(policy_type_id)["create_schema"]
164         validate(instance=instance, schema=schema)
165
166         # store the instance
167         data.store_policy_instance(policy_type_id, policy_instance_id, instance)
168
169         # send rmr (best effort)
170         body = _gen_body_to_handler("CREATE", policy_type_id, policy_instance_id, payload=instance)
171         a1rmr.queue_work({"payload": json.dumps(body), "msg type": policy_type_id})
172
173         return "", 202
174
175     return _try_func_return(put_instance_handler)
176
177
178 def delete_policy_instance(policy_type_id, policy_instance_id):
179     """
180     Handles DELETE /a1-p/policytypes/polidyid/policies/policy_instance_id
181     """
182
183     def delete_instance_handler():
184         """
185         here we send out the DELETEs but we don't delete the instance until a GET is called where we check the statuses
186         """
187         data.instance_is_valid(policy_type_id, policy_instance_id)
188
189         # send rmr (best effort)
190         body = _gen_body_to_handler("DELETE", policy_type_id, policy_instance_id)
191         a1rmr.queue_work({"payload": json.dumps(body), "msg type": policy_type_id})
192
193         return "", 202
194
195     return _try_func_return(delete_instance_handler)