1 # -------------------------------------------------------------------------
2 # Copyright (c) 2020 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 # -------------------------------------------------------------------------
22 from flask import Flask
24 from flask import Response
25 import mysql.connector
27 from osdf.config.base import osdf_config
28 from osdf.logging.osdf_logging import debug_log
29 from osdf.logging.osdf_logging import error_log
30 from osdf.operation.exceptions import BusinessException
31 from osdf.utils.data_conversion import decode_data
40 """Opens a new database connection if there is none yet for the current application context.
43 if not hasattr(g, 'pg'):
44 properties = osdf_config['deployment']
45 host, db_port, db = properties["osdfDatabaseHost"], properties["osdfDatabasePort"], properties.get(
47 user, password = properties["osdfDatabaseUsername"], properties["osdfDatabasePassword"]
48 g.pg = mysql.connector.connect(host=host, port=db_port, user=user, password=password, database=db)
53 """Closes the database again at the end of the request.
63 def create_model_data(model_api):
64 with app.app_context():
66 model_info = model_api['modelInfo']
67 model_id = model_info['modelId']
69 "persisting model_api {}".format(model_id))
71 cursor = connection.cursor(buffered=True)
72 query = "SELECT model_id FROM optim_model_data WHERE model_id = %s"
74 cursor.execute(query, values)
75 if cursor.fetchone() is None:
76 query = "INSERT INTO optim_model_data (model_id, model_content, description, solver_type) VALUES " \
78 values = (model_id, model_info['modelContent'], model_info.get('description'), model_info['solver'])
79 cursor.execute(query, values)
82 debug_log.debug("A record successfully inserted for request_id: {}".format(model_id))
83 return retrieve_model_data(model_id)
86 query = "UPDATE optim_model_data SET model_content = %s, description = %s, solver_type = %s where " \
88 values = (model_info['modelContent'], model_info.get('description'), model_info['solver'], model_id)
89 cursor.execute(query, values)
92 return retrieve_model_data(model_id)
94 except Exception as err:
95 error_log.error("error for request_id: {} - {}".format(model_id, traceback.format_exc()))
97 raise BusinessException(err)
100 def retrieve_model_data(model_id):
101 status, resp_data = get_model_data(model_id)
104 resp = json.dumps(build_model_dict(resp_data))
105 return build_response(resp, status)
109 'statusMessage': "Error retrieving the model data for model {} due to {}".format(model_id, resp_data)
111 return build_response(resp, status)
114 def build_model_dict(resp_data, content_needed=True):
115 resp = {'modelId': resp_data[0], 'description': resp_data[2] if resp_data[2] else '',
116 'solver': resp_data[3]}
118 resp.update({'modelContent': decode_data(resp_data[1])})
122 def build_response(resp, status):
123 response = Response(resp, content_type='application/json; charset=utf-8')
124 response.headers.add('content-length', len(resp))
125 response.status_code = status
129 def delete_model_data(model_id):
130 with app.app_context():
132 debug_log.debug("deleting model data given model_id = {}".format(model_id))
133 connection = get_db()
134 cursor = connection.cursor(buffered=True)
135 query = "delete from optim_model_data WHERE model_id = %s"
137 cursor.execute(query, values)
141 "statusMessage": "model data for modelId {} deleted".format(model_id)
143 return build_response(json.dumps(resp), 200)
144 except Exception as err:
145 error_log.error("error deleting model_id: {} - {}".format(model_id, traceback.format_exc()))
147 raise BusinessException(err)
150 def get_model_data(model_id):
151 with app.app_context():
153 debug_log.debug("getting model data given model_id = {}".format(model_id))
155 connection = get_db()
156 cursor = connection.cursor(buffered=True)
157 query = "SELECT model_id, model_content, description, " \
158 "solver_type FROM optim_model_data WHERE model_id = %s"
160 cursor.execute(query, values)
164 rows = cursor.fetchone()
173 return 500, "NOT_FOUND"
175 error_log.error("error for request_id: {} - {}".format(model_id, traceback.format_exc()))
180 def retrieve_all_models():
181 status, resp_data = get_all_models()
185 model_list.append(build_model_dict(r, False))
186 resp = json.dumps(model_list)
187 return build_response(resp, status)
191 'statusMessage': "Error retrieving all the model data due to {}".format(resp_data)
193 return build_response(resp, status)
196 def get_all_models():
197 with app.app_context():
199 debug_log.debug("getting all model data".format())
200 connection = get_db()
201 cursor = connection.cursor(buffered=True)
202 query = "SELECT model_id, model_content, description, solver_type FROM optim_model_data"
204 cursor.execute(query)
208 rows = cursor.fetchall()
213 return 500, "NOT_FOUND"
215 error_log.error("error for request_id: {}".format(traceback.format_exc()))
221 return osdf_config['deployment'].get('isDatabaseEnabled', False)