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 import mysql.connector
23 from flask import g, Flask, Response
25 from osdf.config.base import osdf_config
26 from osdf.logging.osdf_logging import debug_log, error_log
27 from osdf.operation.exceptions import BusinessException
36 """Opens a new database connection if there is none yet for the
37 current application context.
39 if not hasattr(g, 'pg'):
40 properties = osdf_config['deployment']
41 host, db_port, db = properties["osdfDatabaseHost"], properties["osdfDatabasePort"], \
42 properties.get("osdfDatabaseSchema")
43 user, password = properties["osdfDatabaseUsername"], properties["osdfDatabasePassword"]
44 g.pg = mysql.connector.connect(host=host, port=db_port, user=user, password=password, database=db)
49 """Closes the database again at the end of the request."""
57 def create_model_data(model_api):
58 with app.app_context():
60 model_info = model_api['modelInfo']
61 model_id = model_info['modelId']
63 "persisting model_api {}".format(model_id))
65 cursor = connection.cursor(buffered=True)
66 query = "SELECT model_id FROM optim_model_data WHERE model_id = %s"
68 cursor.execute(query, values)
69 if cursor.fetchone() is None:
70 query = "INSERT INTO optim_model_data (model_id, model_content, description, solver_type) VALUES " \
72 values = (model_id, model_info['modelContent'], model_info.get('description'), model_info['solver'])
73 cursor.execute(query, values)
76 debug_log.debug("A record successfully inserted for request_id: {}".format(model_id))
77 return retrieve_model_data(model_id)
80 query = "UPDATE optim_model_data SET model_content = %s, description = %s, solver_type = %s where " \
82 values = (model_info['modelContent'], model_info.get('description'), model_info['solver'], model_id)
83 cursor.execute(query, values)
86 return retrieve_model_data(model_id)
88 except Exception as err:
89 error_log.error("error for request_id: {} - {}".format(model_id, traceback.format_exc()))
91 raise BusinessException(err)
94 def retrieve_model_data(model_id):
95 status, resp_data = get_model_data(model_id)
98 resp = json.dumps(build_model_dict(resp_data))
99 return build_response(resp, status)
103 'statusMessage': "Error retrieving the model data for model {} due to {}".format(model_id, resp_data)
105 return build_response(resp, status)
108 def build_model_dict(resp_data, content_needed=True):
109 resp = {'modelId': resp_data[0], 'description': resp_data[2] if resp_data[2] else '',
110 'solver': resp_data[3]}
112 resp.update({'modelContent': resp_data[1]})
116 def build_response(resp, status):
117 response = Response(resp, content_type='application/json; charset=utf-8')
118 response.headers.add('content-length', len(resp))
119 response.status_code = status
123 def delete_model_data(model_id):
124 with app.app_context():
126 debug_log.debug("deleting model data given model_id = {}".format(model_id))
128 connection = get_db()
129 cursor = connection.cursor(buffered=True)
130 query = "delete from optim_model_data WHERE model_id = %s"
132 cursor.execute(query, values)
136 "statusMessage": "model data for modelId {} deleted".format(model_id)
138 return build_response(json.dumps(resp), 200)
139 except Exception as err:
140 error_log.error("error deleting model_id: {} - {}".format(model_id, traceback.format_exc()))
142 raise BusinessException(err)
145 def get_model_data(model_id):
146 with app.app_context():
148 debug_log.debug("getting model data given model_id = {}".format(model_id))
150 connection = get_db()
151 cursor = connection.cursor(buffered=True)
152 query = "SELECT model_id, model_content, description, solver_type FROM optim_model_data WHERE model_id = %s"
154 cursor.execute(query, values)
158 rows = cursor.fetchone()
167 return 500, "NOT_FOUND"
169 error_log.error("error for request_id: {} - {}".format(model_id, traceback.format_exc()))
174 def retrieve_all_models():
175 status, resp_data = get_all_models()
179 model_list.append(build_model_dict(r, False))
180 resp = json.dumps(model_list)
181 return build_response(resp, status)
185 'statusMessage': "Error retrieving all the model data due to {}".format(resp_data)
187 return build_response(resp, status)
190 def get_all_models():
191 with app.app_context():
193 debug_log.debug("getting all model data".format())
194 connection = get_db()
195 cursor = connection.cursor(buffered=True)
196 query = "SELECT model_id, model_content, description, solver_type FROM optim_model_data"
198 cursor.execute(query)
202 rows = cursor.fetchall()
207 return 500, "NOT_FOUND"
209 error_log.error("error for request_id: {}".format(traceback.format_exc()))
215 return osdf_config['deployment'].get('isDatabaseEnabled', False)