Merge "OOF design framework seed 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.datasources.aai.aai_local_cached_data
35 import osdf.operation.error_handling
36 import osdf.operation.responses
37 import traceback
38 from osdf.adapters.policy.interface import get_policies
39 from osdf.adapters.response_parsing.aots_ueb_cm_data import aots_ds_ueb_listener
40 from osdf.config.base import osdf_config, DOCKER_CM_OPTIMIZER, AOTS_CM_MESSAGE_BUS
41 from osdf.optimizers.cmopt.rcscheduler.local_opt_processor import process_local_cm_scheduler_opt
42 from osdf.optimizers.placementopt.conductor.remote_opt_processor import process_placement_opt
43 from osdf.webapp.appcontroller import auth_basic
44 from optparse import OptionParser
45 from osdf.operation.exceptions import BusinessException
46 from osdf.operation.error_handling import request_exception_to_json_body, internal_error_message
47 from requests import RequestException
48 from schematics.exceptions import DataError
49 from osdf.logging.osdf_logging import MH, audit_log, error_log
50 from osdf.models.placementRequest import PlacementAPI
51 from osdf.models.schedulerRequest import SchedulerAPI
52
53 ERROR_TEMPLATE = osdf.ERROR_TEMPLATE
54
55 app = Flask(__name__)
56
57
58
59 BAD_CLIENT_REQUEST_MESSAGE = 'Client sent an invalid request'
60
61 # An exception explicitly raised due to some business rule
62 @app.errorhandler(BusinessException)
63 def handle_business_exception(e):
64     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
65     err_msg = ERROR_TEMPLATE.render(description=str(e))
66     response = Response(err_msg, content_type='application/json; charset=utf-8')
67     response.status_code = 400
68     return response
69
70 # Returns a detailed synchronous message to the calling client when osdf fails due to a remote call to another system
71 @app.errorhandler(RequestException)
72 def handle_request_exception(e):
73     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
74     err_msg = request_exception_to_json_body(e)
75     response = Response(err_msg, content_type='application/json; charset=utf-8')
76     response.status_code = 400
77     return response
78
79 # Returns a detailed message to the calling client when the initial synchronous message is invalid
80 @app.errorhandler(DataError)
81 def handle_data_error(e):
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.messages),
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("/osdf/api/v2/placement", methods=["POST"])
99 @auth_basic.login_required
100 def do_placement_opt():
101     """Perform placement optimization after validating the request and fetching policies
102     Make a call to the call-back URL with the output of the placement request.
103     Note: Call to Conductor for placement optimization may have redirects, so account for them
104     """
105     request_json = request.get_json()
106     req_id = request_json['requestInfo']['requestId']
107     g.request_id = req_id
108     audit_log.info(MH.received_request(request.url, request.remote_addr, json.dumps(request_json)))
109
110     PlacementAPI(request_json).validate()
111
112     # Currently policies are being used only during placement, so only fetch them if placement demands is not empty
113     policies = {}
114
115     if 'placementDemand' in request_json['placementInfo']['demandInfo']:
116         policies, prov_status = get_policies(request_json, "placement")
117
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, prov_status))
120     t.start()
121     audit_log.info(MH.accepted_valid_request(req_id, request))
122     return osdf.operation.responses.osdf_response_for_request_accept(
123         req_id=req_id, text="Accepted placement request. Response will be posted to callback URL")
124
125
126 # Returned when unexpected coding errors occur during initial synchronous processing
127 @app.errorhandler(500)
128 def interal_failure(error):
129     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
130     response = Response(internal_error_message, content_type='application/json; charset=utf-8')
131     response.status_code = 500
132     return response
133
134
135 def getOptions(argv):
136     program_version_string = '%%prog %s' % ("v1.0")
137     #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
138     program_longdesc = ""
139     program_license = ""
140
141     # setup option parser
142     parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
143     parser.add_option("-l", "--local", dest="local", help="run locally", action="store_true", default=False)
144     parser.add_option("-t", "--devtest", dest="devtest", help="run in dev/test environment", action="store_true", default=False)
145     parser.add_option("-d", "--debughost", dest="debughost", help="IP Address of host running debug server", default='')
146     parser.add_option("-p", "--debugport", dest="debugport", help="Port number of debug server", type=int, default=5678)
147     (opts, args) = parser.parse_args(argv)
148     if (opts.debughost != ''):
149         print('pydevd.settrace(%s, port=%s)' % (opts.debughost, opts.debugport))
150         pydevd.settrace(opts.debughost, port=opts.debugport)
151     return opts
152
153
154 if __name__ == "__main__":
155
156     sys_conf = osdf_config['core']['osdf_system']
157     ports = sys_conf['osdf_ports']
158     internal_port, external_port = ports['internal'], ports['external']
159     ssl_context = tuple(sys_conf['ssl_context'])
160
161     common_app_opts = dict(host='0.0.0.0', threaded=True, use_reloader=False)
162
163     opts = getOptions(sys.argv)
164     if (opts.local == False and opts.devtest == False):  # normal deployment
165         app.run(port=internal_port, ssl_context=ssl_context, debug=False, **common_app_opts)
166     else:
167         port = internal_port if opts.local == True else external_port
168         app.run(port=port, debug=True, **common_app_opts)