sql_lab.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # pylint: disable=C,R,W
  2. from datetime import datetime
  3. import logging
  4. from time import sleep
  5. import uuid
  6. from celery.exceptions import SoftTimeLimitExceeded
  7. from contextlib2 import contextmanager
  8. import simplejson as json
  9. import sqlalchemy
  10. from sqlalchemy.orm import sessionmaker
  11. from sqlalchemy.pool import NullPool
  12. from superset import app, dataframe, db, results_backend, security_manager
  13. from superset.models.sql_lab import Query
  14. from superset.sql_parse import SupersetQuery
  15. from superset.utils import (
  16. get_celery_app,
  17. json_iso_dttm_ser,
  18. now_as_float,
  19. QueryStatus,
  20. zlib_compress,
  21. )
  22. config = app.config
  23. celery_app = get_celery_app(config)
  24. stats_logger = app.config.get('STATS_LOGGER')
  25. SQLLAB_TIMEOUT = config.get('SQLLAB_ASYNC_TIME_LIMIT_SEC', 600)
  26. class SqlLabException(Exception):
  27. pass
  28. def get_query(query_id, session, retry_count=5):
  29. """attemps to get the query and retry if it cannot"""
  30. query = None
  31. attempt = 0
  32. while not query and attempt < retry_count:
  33. try:
  34. query = session.query(Query).filter_by(id=query_id).one()
  35. except Exception:
  36. attempt += 1
  37. logging.error(
  38. 'Query with id `{}` could not be retrieved'.format(query_id))
  39. stats_logger.incr('error_attempting_orm_query_' + str(attempt))
  40. logging.error('Sleeping for a sec before retrying...')
  41. sleep(1)
  42. if not query:
  43. stats_logger.incr('error_failed_at_getting_orm_query')
  44. raise SqlLabException('Failed at getting query')
  45. return query
  46. @contextmanager
  47. def session_scope(nullpool):
  48. """Provide a transactional scope around a series of operations."""
  49. if nullpool:
  50. engine = sqlalchemy.create_engine(
  51. app.config.get('SQLALCHEMY_DATABASE_URI'), poolclass=NullPool)
  52. session_class = sessionmaker()
  53. session_class.configure(bind=engine)
  54. session = session_class()
  55. else:
  56. session = db.session()
  57. session.commit() # HACK
  58. try:
  59. yield session
  60. session.commit()
  61. except Exception as e:
  62. session.rollback()
  63. logging.exception(e)
  64. raise
  65. finally:
  66. session.close()
  67. @celery_app.task(bind=True, soft_time_limit=SQLLAB_TIMEOUT)
  68. def get_sql_results(
  69. ctask, query_id, rendered_query, return_results=True, store_results=False,
  70. user_name=None, start_time=None):
  71. """Executes the sql query returns the results."""
  72. with session_scope(not ctask.request.called_directly) as session:
  73. try:
  74. return execute_sql(
  75. ctask, query_id, rendered_query, return_results, store_results, user_name,
  76. session=session, start_time=start_time)
  77. except Exception as e:
  78. logging.exception(e)
  79. stats_logger.incr('error_sqllab_unhandled')
  80. query = get_query(query_id, session)
  81. query.error_message = str(e)
  82. query.status = QueryStatus.FAILED
  83. query.tmp_table_name = None
  84. session.commit()
  85. raise
  86. def execute_sql(
  87. ctask, query_id, rendered_query, return_results=True, store_results=False,
  88. user_name=None, session=None, start_time=None,
  89. ):
  90. """Executes the sql query returns the results."""
  91. if store_results and start_time:
  92. # only asynchronous queries
  93. stats_logger.timing(
  94. 'sqllab.query.time_pending', now_as_float() - start_time)
  95. query = get_query(query_id, session)
  96. payload = dict(query_id=query_id)
  97. database = query.database
  98. db_engine_spec = database.db_engine_spec
  99. db_engine_spec.patch()
  100. def handle_error(msg):
  101. """Local method handling error while processing the SQL"""
  102. troubleshooting_link = config['TROUBLESHOOTING_LINK']
  103. query.error_message = msg
  104. query.status = QueryStatus.FAILED
  105. query.tmp_table_name = None
  106. session.commit()
  107. payload.update({
  108. 'status': query.status,
  109. 'error': msg,
  110. })
  111. if troubleshooting_link:
  112. payload['link'] = troubleshooting_link
  113. return payload
  114. if store_results and not results_backend:
  115. return handle_error("Results backend isn't configured.")
  116. # Limit enforced only for retrieving the data, not for the CTA queries.
  117. superset_query = SupersetQuery(rendered_query)
  118. executed_sql = superset_query.stripped()
  119. SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW')
  120. if not superset_query.is_readonly() and not database.allow_dml:
  121. return handle_error(
  122. 'Only `SELECT` statements are allowed against this database')
  123. if query.select_as_cta:
  124. if not superset_query.is_select():
  125. return handle_error(
  126. 'Only `SELECT` statements can be used with the CREATE TABLE '
  127. 'feature.')
  128. if not query.tmp_table_name:
  129. start_dttm = datetime.fromtimestamp(query.start_time)
  130. query.tmp_table_name = 'tmp_{}_table_{}'.format(
  131. query.user_id, start_dttm.strftime('%Y_%m_%d_%H_%M_%S'))
  132. executed_sql = superset_query.as_create_table(query.tmp_table_name)
  133. query.select_as_cta_used = True
  134. if (superset_query.is_select() and SQL_MAX_ROWS and
  135. (not query.limit or query.limit > SQL_MAX_ROWS)):
  136. query.limit = SQL_MAX_ROWS
  137. executed_sql = database.apply_limit_to_sql(executed_sql, query.limit)
  138. # Hook to allow environment-specific mutation (usually comments) to the SQL
  139. SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
  140. if SQL_QUERY_MUTATOR:
  141. executed_sql = SQL_QUERY_MUTATOR(
  142. executed_sql, user_name, security_manager, database)
  143. query.executed_sql = executed_sql
  144. query.status = QueryStatus.RUNNING
  145. query.start_running_time = now_as_float()
  146. session.merge(query)
  147. session.commit()
  148. logging.info("Set query to 'running'")
  149. conn = None
  150. try:
  151. engine = database.get_sqla_engine(
  152. schema=query.schema,
  153. nullpool=True,
  154. user_name=user_name,
  155. )
  156. conn = engine.raw_connection()
  157. cursor = conn.cursor()
  158. logging.info('Running query: \n{}'.format(executed_sql))
  159. logging.info(query.executed_sql)
  160. query_start_time = now_as_float()
  161. db_engine_spec.execute(cursor, query.executed_sql, async_=True)
  162. logging.info('Handling cursor')
  163. db_engine_spec.handle_cursor(cursor, query, session)
  164. logging.info('Fetching data: {}'.format(query.to_dict()))
  165. stats_logger.timing(
  166. 'sqllab.query.time_executing_query',
  167. now_as_float() - query_start_time)
  168. fetching_start_time = now_as_float()
  169. data = db_engine_spec.fetch_data(cursor, query.limit)
  170. stats_logger.timing(
  171. 'sqllab.query.time_fetching_results',
  172. now_as_float() - fetching_start_time)
  173. except SoftTimeLimitExceeded as e:
  174. logging.exception(e)
  175. if conn is not None:
  176. conn.close()
  177. return handle_error(
  178. "SQL Lab timeout. This environment's policy is to kill queries "
  179. 'after {} seconds.'.format(SQLLAB_TIMEOUT))
  180. except Exception as e:
  181. logging.exception(e)
  182. if conn is not None:
  183. conn.close()
  184. return handle_error(db_engine_spec.extract_error_message(e))
  185. logging.info('Fetching cursor description')
  186. cursor_description = cursor.description
  187. if conn is not None:
  188. conn.commit()
  189. conn.close()
  190. if query.status == QueryStatus.STOPPED:
  191. return handle_error('The query has been stopped')
  192. cdf = dataframe.SupersetDataFrame(data, cursor_description, db_engine_spec)
  193. query.rows = cdf.size
  194. query.progress = 100
  195. query.status = QueryStatus.SUCCESS
  196. if query.select_as_cta:
  197. query.select_sql = '{}'.format(
  198. database.select_star(
  199. query.tmp_table_name,
  200. limit=query.limit,
  201. schema=database.force_ctas_schema,
  202. show_cols=False,
  203. latest_partition=False))
  204. query.end_time = now_as_float()
  205. session.merge(query)
  206. session.flush()
  207. payload.update({
  208. 'status': query.status,
  209. 'data': cdf.data if cdf.data else [],
  210. 'columns': cdf.columns if cdf.columns else [],
  211. 'query': query.to_dict(),
  212. })
  213. if store_results:
  214. key = '{}'.format(uuid.uuid4())
  215. logging.info('Storing results in results backend, key: {}'.format(key))
  216. write_to_results_backend_start = now_as_float()
  217. json_payload = json.dumps(
  218. payload, default=json_iso_dttm_ser, ignore_nan=True)
  219. cache_timeout = database.cache_timeout
  220. if cache_timeout is None:
  221. cache_timeout = config.get('CACHE_DEFAULT_TIMEOUT', 0)
  222. results_backend.set(key, zlib_compress(json_payload), cache_timeout)
  223. query.results_key = key
  224. stats_logger.timing(
  225. 'sqllab.query.results_backend_write',
  226. now_as_float() - write_to_results_backend_start)
  227. session.merge(query)
  228. session.commit()
  229. if return_results:
  230. return payload