New policies and required code changes
[optf/osdf.git] / osdfapp.py
index a2af0bf..6854061 100755 (executable)
@@ -43,44 +43,46 @@ from osdf.operation.exceptions import BusinessException
 from osdf.operation.error_handling import request_exception_to_json_body, internal_error_message
 from requests import RequestException
 from schematics.exceptions import DataError
-from osdf.logging.osdf_logging import MH, audit_log, error_log
+from osdf.logging.osdf_logging import MH, audit_log, error_log, debug_log
 from osdf.models.api.placementRequest import PlacementAPI
 
 ERROR_TEMPLATE = osdf.ERROR_TEMPLATE
 
 app = Flask(__name__)
 
-
-
 BAD_CLIENT_REQUEST_MESSAGE = 'Client sent an invalid request'
 
-# An exception explicitly raised due to some business rule
+
 @app.errorhandler(BusinessException)
 def handle_business_exception(e):
+    """An exception explicitly raised due to some business rule"""
     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
     err_msg = ERROR_TEMPLATE.render(description=str(e))
     response = Response(err_msg, content_type='application/json; charset=utf-8')
     response.status_code = 400
     return response
 
-# Returns a detailed synchronous message to the calling client when osdf fails due to a remote call to another system
+
 @app.errorhandler(RequestException)
 def handle_request_exception(e):
+    """Returns a detailed synchronous message to the calling client
+    when osdf fails due to a remote call to another system"""
     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
     err_msg = request_exception_to_json_body(e)
     response = Response(err_msg, content_type='application/json; charset=utf-8')
     response.status_code = 400
     return response
 
-# Returns a detailed message to the calling client when the initial synchronous message is invalid
+
 @app.errorhandler(DataError)
 def handle_data_error(e):
+    """Returns a detailed message to the calling client when the initial synchronous message is invalid"""
     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
 
     body_dictionary = {
         "serviceException": {
             "text": BAD_CLIENT_REQUEST_MESSAGE,
-            "exceptionMessage": str(e.messages),
+            "exceptionMessage": str(e.errors),
             "errorType": "InvalidClientRequest"
         }
     }
@@ -91,7 +93,7 @@ def handle_data_error(e):
     return response
 
 
-@app.route("/osdf/api/v2/placement", methods=["POST"])
+@app.route("/api/oof/v1/placement", methods=["POST"])
 @auth_basic.login_required
 def do_placement_opt():
     """Perform placement optimization after validating the request and fetching policies
@@ -106,7 +108,7 @@ def do_placement_opt():
     PlacementAPI(request_json).validate()
 
     # Currently policies are being used only during placement, so only fetch them if placement demands is not empty
-    policies = {}
+    policies, prov_status = {}, None
 
     if 'placementDemand' in request_json['placementInfo']['demandInfo']:
         policies, prov_status = get_policies(request_json, "placement")
@@ -119,9 +121,9 @@ def do_placement_opt():
         req_id=req_id, text="Accepted placement request. Response will be posted to callback URL")
 
 
-# Returned when unexpected coding errors occur during initial synchronous processing
 @app.errorhandler(500)
 def internal_failure(error):
+    """Returned when unexpected coding errors occur during initial synchronous processing"""
     error_log.error("Synchronous error for request id {} {}".format(g.request_id, traceback.format_exc()))
     response = Response(internal_error_message, content_type='application/json; charset=utf-8')
     response.status_code = 500
@@ -129,19 +131,20 @@ def internal_failure(error):
 
 
 def get_options(argv):
-    program_version_string = '%%prog %s' % ("v1.0")
+    program_version_string = '%%prog %s' % "v1.0"
     program_longdesc = ""
     program_license = ""
 
     parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
     parser.add_option("-l", "--local", dest="local", help="run locally", action="store_true", default=False)
-    parser.add_option("-t", "--devtest", dest="devtest", help="run in dev/test environment", action="store_true", default=False)
+    parser.add_option("-t", "--devtest", dest="devtest", help="run in dev/test environment", action="store_true",
+                      default=False)
     parser.add_option("-d", "--debughost", dest="debughost", help="IP Address of host running debug server", default='')
     parser.add_option("-p", "--debugport", dest="debugport", help="Port number of debug server", type=int, default=5678)
-    (opts, args) = parser.parse_args(argv)
+    opts, args = parser.parse_args(argv)
 
-    if (opts.debughost != ''):
-        print('pydevd.settrace(%s, port=%s)' % (opts.debughost, opts.debugport))
+    if opts.debughost:
+        debug_log.debug('pydevd.settrace({}, port={})'.format(opts.debughost, opts.debugport))
         pydevd.settrace(opts.debughost, port=opts.debugport)
     return opts
 
@@ -151,14 +154,17 @@ if __name__ == "__main__":
     sys_conf = osdf_config['core']['osdf_system']
     ports = sys_conf['osdf_ports']
     internal_port, external_port = ports['internal'], ports['external']
-    ssl_context = tuple(sys_conf['ssl_context'])
-    local_host = "0.0.0.0"  # NOSONAR
 
+    local_host = sys_conf['osdf_ip_default']
     common_app_opts = dict(host=local_host, threaded=True, use_reloader=False)
 
+    ssl_opts = sys_conf.get('ssl_context')
+    if ssl_opts:
+        common_app_opts.update({'ssl_context': tuple(ssl_opts)})
+
     opts = get_options(sys.argv)
-    if (not opts.local and not opts.devtest):  # normal deployment
-        app.run(port=internal_port, ssl_context=ssl_context, debug=False, **common_app_opts)
+    if not opts.local and not opts.devtest:  # normal deployment
+        app.run(port=internal_port, debug=False, **common_app_opts)
     else:
         port = internal_port if opts.local else external_port
         app.run(port=port, debug=True, **common_app_opts)