Initial checkin for pci optimization code
[optf/osdf.git] / osdfapp.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
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 #
16 # -------------------------------------------------------------------------
17 #
18
19 """
20 OSDF Manager Main Flask Application
21 """
22
23 import sys
24 from threading import Thread  # for scaling up, may need celery with RabbitMQ or redis
25
26 from flask import Flask, request, Response, g
27
28 import osdf
29 import pydevd
30 import json
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
36 import traceback
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.models.api.pciOptimizationRequest import PCIOptimizationAPI
49 from osdf.operation.responses import osdf_response_for_request_accept as req_accept
50 from osdf.optimizers.routeopt.simple_route_opt import RouteOpt
51 from osdf.optimizers.pciopt.pci_opt_processor import process_pci_optimation
52
53 ERROR_TEMPLATE = osdf.ERROR_TEMPLATE
54
55 app = Flask(__name__)
56
57 BAD_CLIENT_REQUEST_MESSAGE = 'Client sent an invalid request'
58
59
60 @app.errorhandler(BusinessException)
61 def handle_business_exception(e):
62     """An exception explicitly raised due to some business rule"""
63     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
64     err_msg = ERROR_TEMPLATE.render(description=str(e))
65     response = Response(err_msg, content_type='application/json; charset=utf-8')
66     response.status_code = 400
67     return response
68
69
70 @app.errorhandler(RequestException)
71 def handle_request_exception(e):
72     """Returns a detailed synchronous message to the calling client
73     when osdf fails due to a remote call to another system"""
74     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
75     err_msg = request_exception_to_json_body(e)
76     response = Response(err_msg, content_type='application/json; charset=utf-8')
77     response.status_code = 400
78     return response
79
80
81 @app.errorhandler(DataError)
82 def handle_data_error(e):
83     """Returns a detailed message to the calling client when the initial synchronous message is invalid"""
84     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
85
86     body_dictionary = {
87         "serviceException": {
88             "text": BAD_CLIENT_REQUEST_MESSAGE,
89             "exceptionMessage": str(e.errors),
90             "errorType": "InvalidClientRequest"
91         }
92     }
93
94     body_as_json = json.dumps(body_dictionary)
95     response = Response(body_as_json, content_type='application/json; charset=utf-8')
96     response.status_code = 400
97     return response
98
99
100 @app.route("/api/oof/v1/healthcheck", methods=["GET"])
101 def do_osdf_health_check():
102     """Simple health check"""
103     audit_log.info("A health check request is processed!")
104     return "OK"
105
106
107 @app.route("/api/oof/v1/placement", methods=["POST"])
108 @auth_basic.login_required
109 def do_placement_opt():
110     """Perform placement optimization after validating the request and fetching policies
111     Make a call to the call-back URL with the output of the placement request.
112     Note: Call to Conductor for placement optimization may have redirects, so account for them
113     """
114     request_json = request.get_json()
115     req_id = request_json['requestInfo']['requestId']
116     g.request_id = req_id
117     audit_log.info(MH.received_request(request.url, request.remote_addr, json.dumps(request_json)))
118     PlacementAPI(request_json).validate()
119     policies = get_policies(request_json, "placement")
120     audit_log.info(MH.new_worker_thread(req_id, "[for placement]"))
121     t = Thread(target=process_placement_opt, args=(request_json, policies, osdf_config))
122     t.start()
123     audit_log.info(MH.accepted_valid_request(req_id, request))
124     return req_accept(request_id=req_id,
125                       transaction_id=request_json['requestInfo']['transactionId'],
126                       request_status="accepted", status_message="")
127
128
129 @app.route("/api/oof/v1/route", methods=["POST"])
130 def do_route_calc():
131     """
132     Perform the basic route calculations and returnn the vpn-bindings
133     """
134     request_json = request.get_json()
135     audit_log.info("Calculate Route request received!")
136     src_access_node_id = ""
137     dst_access_node_id = ""
138     try:
139         src_access_node_id = request_json["srcPort"]["src-access-node-id"]
140         audit_log.info( src_access_node_id )
141         dst_access_node_id = request_json["dstPort"]["dst-access-node-id"]
142     except Exception as ex:
143         error_log.error("Exception while retriving the src and dst node info")
144     # for the case of request_json for same domain, return the same node with destination update
145     if src_access_node_id == dst_access_node_id:
146         audit_log.info("src and dst are same")
147         data = '{'\
148                 '"vpns":['\
149                     '{'\
150                         '"access-topology-id": "' + request_json["srcPort"]["src-access-topology-id"] + '",'\
151                         '"access-client-id": "' + request_json["srcPort"]["src-access-client-id"] + '",'\
152                         '"access-provider-id": "' + request_json["srcPort"]["src-access-provider-id"]+ '",'\
153                         '"access-node-id": "' + request_json["srcPort"]["src-access-node-id"]+ '",'\
154                         '"src-access-ltp-id": "' + request_json["srcPort"]["src-access-ltp-id"]+ '",'\
155                         '"dst-access-ltp-id": "' + request_json["dstPort"]["dst-access-ltp-id"]  +'"'\
156                     '}'\
157                 ']'\
158             '}'
159         return data
160     else:
161         return RouteOpt.getRoute(request_json)
162
163 @app.route("/api/oof/v1/pci", methods=["POST"])
164 @auth_basic.login_required
165 def do_pci_optimization():
166     request_json = request.get_json()
167     req_id = request_json['requestInfo']['requestId']
168     g.request_id = req_id
169     audit_log.info(MH.received_request(request.url, request.remote_addr, json.dumps(request_json)))
170     PCIOptimizationAPI(request_json).validate()
171     policies = get_policies(request_json, "pciopt")
172     audit_log.info(MH.new_worker_thread(req_id, "[for pciopt]"))
173     t = Thread(target=process_pci_optimation, args=(request_json, policies, osdf_config))
174     t.start()
175     audit_log.info(MH.accepted_valid_request(req_id, request))
176     return req_accept(request_id=req_id,
177                       transaction_id=request_json['requestInfo']['transactionId'],
178                       request_status="accepted", status_message="")
179
180 @app.errorhandler(500)
181 def internal_failure(error):
182     """Returned when unexpected coding errors occur during initial synchronous processing"""
183     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
184     response = Response(internal_error_message, content_type='application/json; charset=utf-8')
185     response.status_code = 500
186     return response
187
188
189 def get_options(argv):
190     program_version_string = '%%prog %s' % "v1.0"
191     program_longdesc = ""
192     program_license = ""
193
194     parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
195     parser.add_option("-l", "--local", dest="local", help="run locally", action="store_true", default=False)
196     parser.add_option("-t", "--devtest", dest="devtest", help="run in dev/test environment", action="store_true",
197                       default=False)
198     parser.add_option("-d", "--debughost", dest="debughost", help="IP Address of host running debug server", default='')
199     parser.add_option("-p", "--debugport", dest="debugport", help="Port number of debug server", type=int, default=5678)
200     opts, args = parser.parse_args(argv)
201
202     if opts.debughost:
203         debug_log.debug('pydevd.settrace({}, port={})'.format(opts.debughost, opts.debugport))
204         pydevd.settrace(opts.debughost, port=opts.debugport)
205     return opts
206
207
208 if __name__ == "__main__":
209
210     sys_conf = osdf_config['core']['osdf_system']
211     ports = sys_conf['osdf_ports']
212     internal_port, external_port = ports['internal'], ports['external']
213
214     local_host = sys_conf['osdf_ip_default']
215     common_app_opts = dict(host=local_host, threaded=True, use_reloader=False)
216
217     ssl_opts = sys_conf.get('ssl_context')
218     if ssl_opts:
219         common_app_opts.update({'ssl_context': tuple(ssl_opts)})
220
221     opts = get_options(sys.argv)
222     if not opts.local and not opts.devtest:  # normal deployment
223         app.run(port=internal_port, debug=False, **common_app_opts)
224     else:
225         port = internal_port if opts.local else external_port
226         app.run(port=port, debug=True, **common_app_opts)