Merge "Automate the process of policy model uploading"
[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 json
24 import sys
25 import traceback
26 from optparse import OptionParser
27 from threading import Thread  # for scaling up, may need celery with RabbitMQ or redis
28
29 import pydevd
30 from flask import Flask, request, Response, g
31 from requests import RequestException
32 from schematics.exceptions import DataError
33
34 import osdf.adapters.aaf.sms as sms
35 import osdf.operation.responses
36 from osdf.adapters.policy.interface import get_policies
37 from osdf.adapters.policy.interface import upload_policy_models
38 from osdf.config.base import osdf_config
39 from osdf.logging.osdf_logging import MH, audit_log, error_log, debug_log
40 from osdf.models.api.pciOptimizationRequest import PCIOptimizationAPI
41 from osdf.models.api.placementRequest import PlacementAPI
42 from osdf.operation.error_handling import request_exception_to_json_body, internal_error_message
43 from osdf.operation.exceptions import BusinessException
44 from osdf.operation.responses import osdf_response_for_request_accept as req_accept
45 from osdf.optimizers.pciopt.pci_opt_processor import process_pci_optimation
46 from osdf.optimizers.placementopt.conductor.remote_opt_processor import process_placement_opt
47 from osdf.optimizers.routeopt.simple_route_opt import RouteOpt
48 from osdf.utils import api_data_utils
49 from osdf.webapp.appcontroller import auth_basic
50
51 ERROR_TEMPLATE = osdf.ERROR_TEMPLATE
52
53 app = Flask(__name__)
54
55 BAD_CLIENT_REQUEST_MESSAGE = 'Client sent an invalid request'
56
57
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
65     return response
66
67
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
76     return response
77
78
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()))
83
84     body_dictionary = {
85         "serviceException": {
86             "text": BAD_CLIENT_REQUEST_MESSAGE,
87             "exceptionMessage": str(e.errors),
88             "errorType": "InvalidClientRequest"
89         }
90     }
91
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
95     return response
96
97
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!")
102     """Upload policy models"""
103     response = upload_policy_models()
104     audit_log.info(response)
105     return "OK"
106
107
108 @app.route("/api/oof/v1/placement", methods=["POST"])
109 @auth_basic.login_required
110 def do_placement_opt():
111     return placement_rest_api()
112
113
114 @app.route("/api/oof/placement/v1", methods=["POST"])
115 @auth_basic.login_required
116 def do_placement_opt_common_versioning():
117     return placement_rest_api()
118
119
120 def placement_rest_api():
121     """Perform placement optimization after validating the request and fetching policies
122     Make a call to the call-back URL with the output of the placement request.
123     Note: Call to Conductor for placement optimization may have redirects, so account for them
124     """
125     request_json = request.get_json()
126     req_id = request_json['requestInfo']['requestId']
127     g.request_id = req_id
128     audit_log.info(MH.received_request(request.url, request.remote_addr, json.dumps(request_json)))
129     api_version_info = api_data_utils.retrieve_version_info(request, req_id)
130     PlacementAPI(request_json).validate()
131     policies = get_policies(request_json, "placement")
132     audit_log.info(MH.new_worker_thread(req_id, "[for placement]"))
133     t = Thread(target=process_placement_opt, args=(request_json, policies, osdf_config))
134     t.start()
135     audit_log.info(MH.accepted_valid_request(req_id, request))
136     return req_accept(request_id=req_id,
137                       transaction_id=request_json['requestInfo']['transactionId'],
138                       version_info=api_version_info, request_status="accepted", status_message="")
139
140
141 @app.route("/api/oof/v1/route", methods=["POST"])
142 def do_route_calc():
143     """
144     Perform the basic route calculations and returnn the vpn-bindings
145     """
146     request_json = request.get_json()
147     audit_log.info("Calculate Route request received!")
148     return RouteOpt().getRoute(request_json)
149
150
151 @app.route("/api/oof/v1/pci", methods=["POST"])
152 @app.route("/api/oof/pci/v1", methods=["POST"])
153 @auth_basic.login_required
154 def do_pci_optimization():
155     request_json = request.get_json()
156     req_id = request_json['requestInfo']['requestId']
157     g.request_id = req_id
158     audit_log.info(MH.received_request(request.url, request.remote_addr, json.dumps(request_json)))
159     PCIOptimizationAPI(request_json).validate()
160     # disable policy retrieval
161     # policies = get_policies(request_json, "pciopt")
162     audit_log.info(MH.new_worker_thread(req_id, "[for pciopt]"))
163     t = Thread(target=process_pci_optimation, args=(request_json, osdf_config, None))
164     t.start()
165     audit_log.info(MH.accepted_valid_request(req_id, request))
166     return req_accept(request_id=req_id,
167                       transaction_id=request_json['requestInfo']['transactionId'],
168                       request_status="accepted", status_message="")
169
170
171 @app.errorhandler(500)
172 def internal_failure(error):
173     """Returned when unexpected coding errors occur during initial synchronous processing"""
174     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
175     response = Response(internal_error_message, content_type='application/json; charset=utf-8')
176     response.status_code = 500
177     return response
178
179
180 def get_options(argv):
181     program_version_string = '%%prog %s' % "v1.0"
182     program_longdesc = ""
183     program_license = ""
184
185     parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
186     parser.add_option("-l", "--local", dest="local", help="run locally", action="store_true", default=False)
187     parser.add_option("-t", "--devtest", dest="devtest", help="run in dev/test environment", action="store_true",
188                       default=False)
189     parser.add_option("-d", "--debughost", dest="debughost", help="IP Address of host running debug server", default='')
190     parser.add_option("-p", "--debugport", dest="debugport", help="Port number of debug server", type=int, default=5678)
191     opts, args = parser.parse_args(argv)
192
193     if opts.debughost:
194         debug_log.debug('pydevd.settrace({}, port={})'.format(opts.debughost, opts.debugport))
195         pydevd.settrace(opts.debughost, port=opts.debugport)
196     return opts
197
198
199 if __name__ == "__main__":
200
201     sys_conf = osdf_config['core']['osdf_system']
202     ports = sys_conf['osdf_ports']
203     internal_port, external_port = ports['internal'], ports['external']
204
205     local_host = sys_conf['osdf_ip_default']
206     common_app_opts = dict(host=local_host, threaded=True, use_reloader=False)
207
208     ssl_opts = sys_conf.get('ssl_context')
209     if ssl_opts:
210         common_app_opts.update({'ssl_context': tuple(ssl_opts)})
211
212     opts = get_options(sys.argv)
213     # Load secrets from SMS
214     sms.load_secrets()
215     if not opts.local and not opts.devtest:  # normal deployment
216         app.run(port=internal_port, debug=False, **common_app_opts)
217     else:
218         port = internal_port if opts.local else external_port
219         app.run(port=port, debug=True, **common_app_opts)