codecoverage improvement
[dcaegen2/platform.git] / mod / distributorapi / distributor / http.py
1 # ============LICENSE_START=======================================================
2 # Copyright (c) 2019-2022 AT&T Intellectual Property. All rights reserved.
3 # ================================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 # ============LICENSE_END=========================================================
16 """Code for http interface"""
17
18 import logging, json
19 import uuid
20 from flask import Flask
21 from flask_cors import CORS
22 import flask_restplus as frp
23 from flask_restplus import Api, Resource, fields
24 from distributor.version import __version__
25 from distributor import data_access as da
26 from distributor import config
27 from distributor import registry_client as rc
28 from distributor import onboarding_client as oc
29 from distributor import runtime_client as runc
30 from distributor import transform as tr
31
32
33 _log = logging.getLogger("distributor.http")
34
35 _app = Flask(__name__)
36 CORS(_app)
37 # Try to bundle as many errors together
38 # https://flask-restplus.readthedocs.io/en/stable/parsing.html#error-handling
39 _app.config["BUNDLE_ERRORS"] = True
40 _api = Api(
41     _app,
42     version=__version__,
43     title="Distributor HTTP API",
44     description="HTTP API to manage distribution targets for DCAE design. Distribution targets are DCAE runtime environments that have been registered and are enabled to accept flow design changes that are to be orchestrated in that environment",
45     contact="",
46     default_mediatype="application/json",
47     prefix="/distributor",
48     doc="/distributor",
49     default="distributor",
50 )
51 # REVIEW: Do I need a namespace?
52 ns = _api
53
54 model_pg = _api.model(
55     "ProcessGroup",
56     {
57         "id": fields.String(required=True, description="Id for this process group", attribute="processGroupId"),
58         "version": fields.Integer(required=True, description="Version of the process group"),
59         "processed": fields.DateTime(required=True, description="When this process group was processed by this API"),
60         "runtimeResponse": fields.String(required=True, description="Full response from the runtime API"),
61     },
62 )
63
64 model_dt = _api.model(
65     "DistributionTarget",
66     {
67         "selfUrl": fields.Url("resource_distribution_target", absolute=True),
68         "id": fields.String(required=True, description="Id for this distribution target", attribute="dt_id"),
69         "name": fields.String(required=True, description="Name for this distribution target", attribute="name"),
70         "runtimeApiUrl": fields.String(
71             required=True, description="Url to the runtime API for this distribution target", attribute="runtimeApiUrl"
72         ),
73         "description": fields.String(
74             required=False, description="Description for this distribution target", attribute="description"
75         ),
76         "nextDistributionTargetId": fields.String(
77             required=False,
78             description="Id to the next distribution target. Distribution targets can be linked together and have a progression order. Specifying the id of the next distribution target defines the next element int the order.",
79             attribute="nextDistributionTargetId",
80         ),
81         "created": fields.String(
82             required=True, description="When this distribution target was created in UTC", attribute="created"
83         ),
84         "modified": fields.String(
85             required=True, description="When this distribution target was last modified in UTC", attribute="modified"
86         ),
87         "processGroups": fields.List(fields.Nested(model_pg)),
88     },
89 )
90
91 model_dts = _api.model("DistributionTargets", {"distributionTargets": fields.List(fields.Nested(model_dt))})
92
93
94 parser_dt_req = ns.parser()
95 parser_dt_req.add_argument(
96     "name", required=True, trim=True, location="json", help="Name for this new distribution target"
97 )
98 parser_dt_req.add_argument(
99     "runtimeApiUrl",
100     required=True,
101     trim=True,
102     location="json",
103     help="Url to the runtime API for this distribution target",
104 )
105 parser_dt_req.add_argument(
106     "description", required=False, trim=True, location="json", help="Description for this distribution target"
107 )
108 parser_dt_req.add_argument(
109     "nextDistributionTargetId",
110     required=False,
111     trim=True,
112     location="json",
113     help="Id of the next distribution target. Distribution targets can be linked together and have a progression order. Specifying the id of the next distribution target defines the next element int the order.",
114 )
115
116
117 @ns.route("/distribution-targets", endpoint="resource_distribution_targets")
118 class DistributionTargets(Resource):
119     @ns.doc("get_distribution_targets", description="List distribution targets")
120     @ns.marshal_with(model_dts)
121     def get(self):
122         return {"distributionTargets": da.get_distribution_targets()}, 200
123
124     @ns.doc("post_distribution_targets", description="Create a new distribution target")
125     @ns.expect(parser_dt_req)
126     @ns.marshal_with(model_dt)
127     def post(self):
128         req = parser_dt_req.parse_args()
129         req = da.transform_request(req)
130         resp = da.add_distribution_target(req)
131         return resp, 200
132
133
134 @ns.route("/distribution-targets/<string:dt_id>", endpoint="resource_distribution_target")
135 class DistributionTarget(Resource):
136     @ns.doc("get_distribution_target", description="Get a distribution target instance")
137     @ns.response(404, "Distribution target not found")
138     @ns.response(500, "Internal Server Error")
139     @ns.marshal_with(model_dt)
140     def get(self, dt_id):
141         result = da.get_distribution_target(dt_id)
142
143         if result:
144             return result, 200
145         else:
146             frp.abort(code=404, message="Unknown distribution target")
147
148     @ns.doc("put_distribution_target", description="Update an existing distribution target")
149     @ns.response(404, "Distribution target not found")
150     @ns.response(500, "Internal Server Error")
151     @ns.expect(parser_dt_req)
152     @ns.marshal_with(model_dt)
153     def put(self, dt_id):
154         result = da.get_distribution_target(dt_id)
155
156         if not result:
157             frp.abort(code=404, message="Unknown distribution target")
158
159         req = parser_dt_req.parse_args()
160         updated_dt = da.merge_request(result, req)
161
162         if da.update_distribution_target(updated_dt):
163             return updated_dt, 200
164         else:
165             frp.abort(code=500, message="Problem with storing the update")
166
167     @ns.response(404, "Distribution target not found")
168     @ns.response(500, "Internal Server Error")
169     @ns.doc("delete_distribution_target", description="Delete an existing distribution target")
170     def delete(self, dt_id):
171         if da.delete_distribution_target(dt_id):
172             return
173         else:
174             frp.abort(code=404, message="Unknown distribution target")
175
176
177 parser_post_process_group = ns.parser()
178 parser_post_process_group.add_argument(
179     "processGroupId", required=True, trim=True, location="json", help="Process group ID that exists in Nifi"
180 )
181
182
183 @ns.route("/distribution-targets/<string:dt_id>/process-groups", endpoint="resource_target_process_groups")
184 class DTargetProcessGroups(Resource):
185     @ns.response(404, "Distribution target not found")
186     @ns.response(501, "Feature is not supported right now")
187     @ns.response(500, "Internal Server Error")
188     @ns.expect(parser_post_process_group)
189     def post(self, dt_id):
190         # TODO: Need bucket ID but for now will simply scan through all buckets
191         # TODO: Current impl doesn't take into consideration the last state of
192         # the distribution target e.g. what was the last design processed
193
194         req = parser_post_process_group.parse_args()
195
196         # Check existence of distribution target
197
198         dtarget = da.get_distribution_target(dt_id)
199
200         if not dtarget:
201             frp.abort(code=404, message="Unknown distribution target")
202
203         runtime_url = dtarget["runtimeApiUrl"]
204         pg_id = req["processGroupId"]
205
206         # Find flow from Nifi registry
207
208         try:
209             flow = rc.find_flow(config.nifi_registry_url, pg_id)
210         except Exception as e:
211             # TODO: Switch to logging
212             print(e)
213             # Assuming it'll be 404
214             frp.abort(code=404, message="Process group not found in registry")
215
216         pg_name = flow["name"]
217
218         # Make sure graph is setup in runtime api
219
220         if runc.ensure_graph(runtime_url, pg_id, pg_name) == False:
221             frp.abort(code=501, message="Runtime API: Graph could not be created")
222
223         # Graph diffing using Nifi registry
224
225         flow_diff = rc.get_flow_diff_latest(config.nifi_registry_url, flow["selfUrl"])
226
227         if flow_diff:
228             # TODO: Not really processing diff right now instead just processing
229             # latest. Later process the diffs instead and send out the changes.
230             flow_latest = rc.get_flow_version_latest(config.nifi_registry_url, flow["selfUrl"])
231         else:
232             flow_latest = rc.get_flow_version(config.nifi_registry_url, flow["selfUrl"], 1)
233
234         # Get component data from onboarding API
235
236         components = tr.extract_components_from_flow(flow_latest)
237
238         try:
239             components = oc.get_components_indexed(config.onboarding_api_url, components)
240         except Exception as e:
241             # TODO: Switch to logging
242             print(e)
243             # Assuming it'll be 404
244             frp.abort(code=404, message="Component not found in onboarding API")
245
246         #
247         # Put everything together, post to runtime API, save
248         #
249
250         actions = tr.make_fbp_from_flow(flow_latest, components)
251
252         resp = dict(req)
253         resp["version"] = flow_latest["snapshotMetadata"]["version"]
254         resp["runtimeResponse"] = json.dumps(runc.post_graph(runtime_url, pg_id, actions))
255         resp = da.add_process_group(dt_id, resp)
256
257         if resp:
258             return resp, 200
259         else:
260             frp.abort(code=500, message="Could not store process group")
261
262
263 def start_http_server():
264     config.init()
265
266     def is_debug():
267         import os
268
269         if os.environ.get("DISTRIBUTOR_DEBUG", "1") == "1":
270             return True
271         else:
272             return False
273
274     if is_debug():
275         _app.run(debug=True)
276     else:
277         _app.run(host="0.0.0.0", port=8080, debug=False)