1 # -------------------------------------------------------------------------
2 # Copyright (c) 2015-2017 AT&T Intellectual Property
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.
16 # -------------------------------------------------------------------------
20 OSDF Manager Main Flask Application
24 from threading import Thread # for scaling up, may need celery with RabbitMQ or redis
26 from flask import Flask, request, Response, g
31 import osdf.adapters.policy.interface
32 import osdf.config.credentials
33 import osdf.config.loader
34 import osdf.operation.error_handling
35 import osdf.operation.responses
37 from osdf.adapters.policy.interface import get_policies
38 from osdf.config.base import osdf_config
39 from osdf.optimizers.placementopt.conductor.remote_opt_processor import process_placement_opt
40 from osdf.webapp.appcontroller import auth_basic
41 from optparse import OptionParser
42 from osdf.operation.exceptions import BusinessException
43 from osdf.operation.error_handling import request_exception_to_json_body, internal_error_message
44 from requests import RequestException
45 from schematics.exceptions import DataError
46 from osdf.logging.osdf_logging import MH, audit_log, error_log, debug_log
47 from osdf.models.api.placementRequest import PlacementAPI
48 from osdf.operation.responses import osdf_response_for_request_accept as req_accept
49 from osdf.optimizers.routeopt.simple_route_opt import RouteOpt
51 ERROR_TEMPLATE = osdf.ERROR_TEMPLATE
55 BAD_CLIENT_REQUEST_MESSAGE = 'Client sent an invalid request'
58 @app.errorhandler(BusinessException)
59 def handle_business_exception(e):
60 """An exception explicitly raised due to some business rule"""
61 error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
62 err_msg = ERROR_TEMPLATE.render(description=str(e))
63 response = Response(err_msg, content_type='application/json; charset=utf-8')
64 response.status_code = 400
68 @app.errorhandler(RequestException)
69 def handle_request_exception(e):
70 """Returns a detailed synchronous message to the calling client
71 when osdf fails due to a remote call to another system"""
72 error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
73 err_msg = request_exception_to_json_body(e)
74 response = Response(err_msg, content_type='application/json; charset=utf-8')
75 response.status_code = 400
79 @app.errorhandler(DataError)
80 def handle_data_error(e):
81 """Returns a detailed message to the calling client when the initial synchronous message is invalid"""
82 error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
86 "text": BAD_CLIENT_REQUEST_MESSAGE,
87 "exceptionMessage": str(e.errors),
88 "errorType": "InvalidClientRequest"
92 body_as_json = json.dumps(body_dictionary)
93 response = Response(body_as_json, content_type='application/json; charset=utf-8')
94 response.status_code = 400
98 @app.route("/api/oof/v1/healthcheck", methods=["GET"])
99 def do_osdf_health_check():
100 """Simple health check"""
101 audit_log.info("A health check request is processed!")
105 @app.route("/api/oof/v1/placement", methods=["POST"])
106 @auth_basic.login_required
107 def do_placement_opt():
108 """Perform placement optimization after validating the request and fetching policies
109 Make a call to the call-back URL with the output of the placement request.
110 Note: Call to Conductor for placement optimization may have redirects, so account for them
112 request_json = request.get_json()
113 req_id = request_json['requestInfo']['requestId']
114 g.request_id = req_id
115 audit_log.info(MH.received_request(request.url, request.remote_addr, json.dumps(request_json)))
116 PlacementAPI(request_json).validate()
117 policies = get_policies(request_json, "placement")
118 audit_log.info(MH.new_worker_thread(req_id, "[for placement]"))
119 t = Thread(target=process_placement_opt, args=(request_json, policies, osdf_config))
121 audit_log.info(MH.accepted_valid_request(req_id, request))
122 return req_accept(request_id=req_id,
123 transaction_id=request_json['requestInfo']['transactionId'],
124 request_status="accepted", status_message="")
127 @app.route("/api/oof/v1/route", methods=["POST"])
130 Perform the basic route calculations and returnn the vpn-bindings
132 request_json = request.get_json()
133 audit_log.info("Calculate Route request received!")
134 src_access_node_id = ""
135 dst_access_node_id = ""
137 src_access_node_id = request_json["srcPort"]["src-access-node-id"]
138 audit_log.info( src_access_node_id )
139 dst_access_node_id = request_json["dstPort"]["dst-access-node-id"]
140 except Exception as ex:
141 error_log.error("Exception while retriving the src and dst node info")
142 # for the case of request_json for same domain, return the same node with destination update
143 if src_access_node_id == dst_access_node_id:
144 audit_log.info("src and dst are same")
148 '"access-topology-id": "' + request_json["srcPort"]["src-access-topology-id"] + '",'\
149 '"access-client-id": "' + request_json["srcPort"]["src-access-client-id"] + '",'\
150 '"access-provider-id": "' + request_json["srcPort"]["src-access-provider-id"]+ '",'\
151 '"access-node-id": "' + request_json["srcPort"]["src-access-node-id"]+ '",'\
152 '"src-access-ltp-id": "' + request_json["srcPort"]["src-access-ltp-id"]+ '",'\
153 '"dst-access-ltp-id": "' + request_json["dstPort"]["dst-access-ltp-id"] +'"'\
159 return RouteOpt.getRoute(request_json)
161 @app.errorhandler(500)
162 def internal_failure(error):
163 """Returned when unexpected coding errors occur during initial synchronous processing"""
164 error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
165 response = Response(internal_error_message, content_type='application/json; charset=utf-8')
166 response.status_code = 500
170 def get_options(argv):
171 program_version_string = '%%prog %s' % "v1.0"
172 program_longdesc = ""
175 parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
176 parser.add_option("-l", "--local", dest="local", help="run locally", action="store_true", default=False)
177 parser.add_option("-t", "--devtest", dest="devtest", help="run in dev/test environment", action="store_true",
179 parser.add_option("-d", "--debughost", dest="debughost", help="IP Address of host running debug server", default='')
180 parser.add_option("-p", "--debugport", dest="debugport", help="Port number of debug server", type=int, default=5678)
181 opts, args = parser.parse_args(argv)
184 debug_log.debug('pydevd.settrace({}, port={})'.format(opts.debughost, opts.debugport))
185 pydevd.settrace(opts.debughost, port=opts.debugport)
189 if __name__ == "__main__":
191 sys_conf = osdf_config['core']['osdf_system']
192 ports = sys_conf['osdf_ports']
193 internal_port, external_port = ports['internal'], ports['external']
195 local_host = sys_conf['osdf_ip_default']
196 common_app_opts = dict(host=local_host, threaded=True, use_reloader=False)
198 ssl_opts = sys_conf.get('ssl_context')
200 common_app_opts.update({'ssl_context': tuple(ssl_opts)})
202 opts = get_options(sys.argv)
203 if not opts.local and not opts.devtest: # normal deployment
204 app.run(port=internal_port, debug=False, **common_app_opts)
206 port = internal_port if opts.local else external_port
207 app.run(port=port, debug=True, **common_app_opts)