1 # ============LICENSE_START=======================================================
2 # Copyright (c) 2019 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
40 _api = Api(_app, version=__version__, title="Distributor HTTP API",
41 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",
42 contact="", default_mediatype="application/json"
43 , prefix="/distributor", doc="/distributor", default="distributor"
45 # REVIEW: Do I need a namespace?
48 model_pg = _api.model("ProcessGroup", {
49 "id": fields.String(required=True, description="Id for this process group"
50 , attribute="processGroupId")
51 , "version": fields.Integer(required=True
52 , description="Version of the process group")
53 , "processed": fields.DateTime(required=True
54 , description="When this process group was processed by this API")
55 , "runtimeResponse": fields.String(required=True
56 , description="Full response from the runtime API")
59 model_dt = _api.model("DistributionTarget", {
60 "selfUrl": fields.Url("resource_distribution_target", absolute=True)
61 , "id": fields.String(required=True, description="Id for this distribution target"
63 , "name": fields.String(required=True, description="Name for this distribution target"
65 , "runtimeApiUrl": fields.String(required=True
66 , description="Url to the runtime API for this distribution target"
67 , attribute="runtimeApiUrl")
68 , "description": fields.String(required=False
69 , description="Description for this distribution target"
70 , attribute="description")
71 , "nextDistributionTargetId": fields.String(required=False
72 , 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."
73 , attribute="nextDistributionTargetId")
74 , "created": fields.String(required=True
75 , description="When this distribution target was created in UTC"
76 , attribute="created")
77 , "modified": fields.String(required=True
78 , description="When this distribution target was last modified in UTC"
79 , attribute="modified")
80 , "processGroups": fields.List(fields.Nested(model_pg))
83 model_dts = _api.model("DistributionTargets", {
84 "distributionTargets": fields.List(fields.Nested(model_dt))
88 parser_dt_req = ns.parser()
89 parser_dt_req.add_argument("name", required=True, trim=True,
90 location="json", help="Name for this new distribution target")
91 parser_dt_req.add_argument("runtimeApiUrl", required=True, trim=True,
92 location="json", help="Url to the runtime API for this distribution target")
93 parser_dt_req.add_argument("description", required=False, trim=True,
94 location="json", help="Description for this distribution target")
95 parser_dt_req.add_argument("nextDistributionTargetId", required=False, trim=True,
96 location="json", 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.")
99 @ns.route("/distribution-targets", endpoint="resource_distribution_targets")
100 class DistributionTargets(Resource):
101 @ns.doc("get_distribution_targets", description="List distribution targets")
102 @ns.marshal_with(model_dts)
104 return { "distributionTargets": da.get_distribution_targets() }, 200
106 @ns.doc("post_distribution_targets", description="Create a new distribution target")
107 @ns.expect(parser_dt_req)
108 @ns.marshal_with(model_dt)
110 req = parser_dt_req.parse_args()
111 req = da.transform_request(req)
112 resp = da.add_distribution_target(req)
115 @ns.route("/distribution-targets/<string:dt_id>", endpoint="resource_distribution_target")
116 class DistributionTarget(Resource):
117 @ns.doc("get_distribution_target", description="Get a distribution target instance")
118 @ns.response(404, 'Distribution target not found')
119 @ns.response(500, 'Internal Server Error')
120 @ns.marshal_with(model_dt)
121 def get(self, dt_id):
122 result = da.get_distribution_target(dt_id)
127 frp.abort(code=404, message="Unknown distribution target")
129 @ns.doc("put_distribution_target", description="Update an existing distribution target")
130 @ns.response(404, 'Distribution target not found')
131 @ns.response(500, 'Internal Server Error')
132 @ns.expect(parser_dt_req)
133 @ns.marshal_with(model_dt)
134 def put(self, dt_id):
135 result = da.get_distribution_target(dt_id)
138 frp.abort(code=404, message="Unknown distribution target")
140 req = parser_dt_req.parse_args()
141 updated_dt = da.merge_request(result, req)
143 if da.update_distribution_target(updated_dt):
144 return updated_dt, 200
146 frp.abort(code=500, message="Problem with storing the update")
148 @ns.response(404, 'Distribution target not found')
149 @ns.response(500, 'Internal Server Error')
150 @ns.doc("delete_distribution_target", description="Delete an existing distribution target")
151 def delete(self, dt_id):
152 if da.delete_distribution_target(dt_id):
155 frp.abort(code=404, message="Unknown distribution target")
158 parser_post_process_group = ns.parser()
159 parser_post_process_group.add_argument("processGroupId", required=True,
160 trim=True, location="json", help="Process group ID that exists in Nifi")
162 @ns.route("/distribution-targets/<string:dt_id>/process-groups", endpoint="resource_target_process_groups")
163 class DTargetProcessGroups(Resource):
165 @ns.response(404, 'Distribution target not found')
166 @ns.response(501, 'Feature is not supported right now')
167 @ns.response(500, 'Internal Server Error')
168 @ns.expect(parser_post_process_group)
169 def post(self, dt_id):
170 # TODO: Need bucket ID but for now will simply scan through all buckets
171 # TODO: Current impl doesn't take into consideration the last state of
172 # the distribution target e.g. what was the last design processed
174 req = parser_post_process_group.parse_args()
176 # Check existence of distribution target
178 dtarget = da.get_distribution_target(dt_id)
181 frp.abort(code=404, message="Unknown distribution target")
183 runtime_url = dtarget["runtimeApiUrl"]
184 pg_id = req["processGroupId"]
186 # Find flow from Nifi registry
189 flow = rc.find_flow(config.nifi_registry_url, pg_id)
190 except Exception as e:
191 # TODO: Switch to logging
193 # Assuming it'll be 404
194 frp.abort(code=404, message="Process group not found in registry")
196 pg_name = flow["name"]
198 # Make sure graph is setup in runtime api
200 if runc.ensure_graph(runtime_url, pg_id, pg_name) == False:
201 frp.abort(code=501 , message="Runtime API: Graph could not be created")
203 # Graph diffing using Nifi registry
205 flow_diff = rc.get_flow_diff_latest(config.nifi_registry_url, flow["selfUrl"])
208 # TODO: Not really processing diff right now instead just processing
209 # latest. Later process the diffs instead and send out the changes.
210 flow_latest = rc.get_flow_version_latest(config.nifi_registry_url, flow["selfUrl"])
212 flow_latest = rc.get_flow_version(config.nifi_registry_url, flow["selfUrl"], 1)
214 # Get component data from onboarding API
216 components = tr.extract_components_from_flow(flow_latest)
219 components = oc.get_components_indexed(config.onboarding_api_url, components)
220 except Exception as e:
221 # TODO: Switch to logging
223 # Assuming it'll be 404
224 frp.abort(code=404, message="Component not found in onboarding API")
227 # Put everything together, post to runtime API, save
230 actions = tr.make_fbp_from_flow(flow_latest, components)
233 resp["version"] = flow_latest["snapshotMetadata"]["version"]
234 resp["runtimeResponse"] = json.dumps(runc.post_graph(runtime_url, pg_id, actions))
235 resp = da.add_process_group(dt_id, resp)
240 frp.abort(code=500, message="Could not store process group")
243 def start_http_server():
248 if os.environ.get("DISTRIBUTOR_DEBUG", "1") == "1":
256 _app.run(host="0.0.0.0", port=8080, debug=False)