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
8 # http://www.apache.org/licenses/LICENSE-2.0
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"""
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
33 _log = logging.getLogger("distributor.http")
35 _app = Flask(__name__)
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
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",
46 default_mediatype="application/json",
47 prefix="/distributor",
49 default="distributor",
51 # REVIEW: Do I need a namespace?
54 model_pg = _api.model(
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"),
64 model_dt = _api.model(
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"
73 "description": fields.String(
74 required=False, description="Description for this distribution target", attribute="description"
76 "nextDistributionTargetId": fields.String(
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",
81 "created": fields.String(
82 required=True, description="When this distribution target was created in UTC", attribute="created"
84 "modified": fields.String(
85 required=True, description="When this distribution target was last modified in UTC", attribute="modified"
87 "processGroups": fields.List(fields.Nested(model_pg)),
91 model_dts = _api.model("DistributionTargets", {"distributionTargets": fields.List(fields.Nested(model_dt))})
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"
98 parser_dt_req.add_argument(
103 help="Url to the runtime API for this distribution target",
105 parser_dt_req.add_argument(
106 "description", required=False, trim=True, location="json", help="Description for this distribution target"
108 parser_dt_req.add_argument(
109 "nextDistributionTargetId",
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.",
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)
122 return {"distributionTargets": da.get_distribution_targets()}, 200
124 @ns.doc("post_distribution_targets", description="Create a new distribution target")
125 @ns.expect(parser_dt_req)
126 @ns.marshal_with(model_dt)
128 req = parser_dt_req.parse_args()
129 req = da.transform_request(req)
130 resp = da.add_distribution_target(req)
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)
146 frp.abort(code=404, message="Unknown distribution target")
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)
157 frp.abort(code=404, message="Unknown distribution target")
159 req = parser_dt_req.parse_args()
160 updated_dt = da.merge_request(result, req)
162 if da.update_distribution_target(updated_dt):
163 return updated_dt, 200
165 frp.abort(code=500, message="Problem with storing the update")
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):
174 frp.abort(code=404, message="Unknown distribution target")
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"
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
194 req = parser_post_process_group.parse_args()
196 # Check existence of distribution target
198 dtarget = da.get_distribution_target(dt_id)
201 frp.abort(code=404, message="Unknown distribution target")
203 runtime_url = dtarget["runtimeApiUrl"]
204 pg_id = req["processGroupId"]
206 # Find flow from Nifi registry
209 flow = rc.find_flow(config.nifi_registry_url, pg_id)
210 except Exception as e:
211 # TODO: Switch to logging
213 # Assuming it'll be 404
214 frp.abort(code=404, message="Process group not found in registry")
216 pg_name = flow["name"]
218 # Make sure graph is setup in runtime api
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")
223 # Graph diffing using Nifi registry
225 flow_diff = rc.get_flow_diff_latest(config.nifi_registry_url, flow["selfUrl"])
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"])
232 flow_latest = rc.get_flow_version(config.nifi_registry_url, flow["selfUrl"], 1)
234 # Get component data from onboarding API
236 components = tr.extract_components_from_flow(flow_latest)
239 components = oc.get_components_indexed(config.onboarding_api_url, components)
240 except Exception as e:
241 # TODO: Switch to logging
243 # Assuming it'll be 404
244 frp.abort(code=404, message="Component not found in onboarding API")
247 # Put everything together, post to runtime API, save
250 actions = tr.make_fbp_from_flow(flow_latest, components)
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)
260 frp.abort(code=500, message="Could not store process group")
263 def start_http_server():
269 if os.environ.get("DISTRIBUTOR_DEBUG", "1") == "1":
277 _app.run(host="0.0.0.0", port=8080, debug=False)