api.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import json
  18. import logging
  19. import sqlparse
  20. import urllib
  21. from django.urls import reverse
  22. from django.db.models import Q
  23. from django.utils.translation import ugettext as _
  24. from django.views.decorators.http import require_GET, require_POST
  25. from desktop.api2 import __paginate
  26. from desktop.conf import TASK_SERVER
  27. from desktop.lib.i18n import smart_str
  28. from desktop.lib.django_util import JsonResponse
  29. from desktop.models import Document2, Document
  30. from indexer.file_format import HiveFormat
  31. from indexer.fields import Field
  32. from notebook.connectors.base import Notebook, QueryExpired, SessionExpired, QueryError, _get_snippet_name
  33. from notebook.connectors.dataeng import DataEngApi
  34. from notebook.connectors.hiveserver2 import HS2Api
  35. from notebook.connectors.oozie_batch import OozieApi
  36. from notebook.decorators import api_error_handler, check_document_access_permission, check_document_modify_permission
  37. from notebook.models import escape_rows, make_notebook
  38. from notebook.views import upgrade_session_properties, get_api
  39. LOG = logging.getLogger(__name__)
  40. DEFAULT_HISTORY_NAME = ''
  41. @require_POST
  42. @api_error_handler
  43. def create_notebook(request):
  44. response = {'status': -1}
  45. editor_type = request.POST.get('type', 'notebook')
  46. directory_uuid = request.POST.get('directory_uuid')
  47. editor = Notebook()
  48. data = editor.get_data()
  49. if editor_type != 'notebook':
  50. data['name'] = ''
  51. data['type'] = 'query-%s' % editor_type # TODO: Add handling for non-SQL types
  52. data['directoryUuid'] = directory_uuid
  53. editor.data = json.dumps(data)
  54. response['notebook'] = editor.get_data()
  55. response['status'] = 0
  56. return JsonResponse(response)
  57. @require_POST
  58. @check_document_access_permission()
  59. @api_error_handler
  60. def create_session(request):
  61. response = {'status': -1}
  62. notebook = json.loads(request.POST.get('notebook', '{}'))
  63. session = json.loads(request.POST.get('session', '{}'))
  64. properties = session.get('properties', [])
  65. response['session'] = get_api(request, session).create_session(lang=session['type'], properties=properties)
  66. response['status'] = 0
  67. return JsonResponse(response)
  68. @require_POST
  69. @check_document_access_permission()
  70. @api_error_handler
  71. def close_session(request):
  72. response = {'status': -1}
  73. session = json.loads(request.POST.get('session', '{}'))
  74. response['session'] = get_api(request, {'type': session['type']}).close_session(session=session)
  75. response['status'] = 0
  76. return JsonResponse(response)
  77. def _execute_notebook(request, notebook, snippet):
  78. response = {'status': -1}
  79. result = None
  80. history = None
  81. historify = (notebook['type'] != 'notebook' or snippet.get('wasBatchExecuted')) and not notebook.get('skipHistorify')
  82. try:
  83. try:
  84. session = notebook.get('sessions') and notebook['sessions'][0] # Session reference for snippet execution without persisting it
  85. if historify:
  86. history = _historify(notebook, request.user)
  87. notebook = Notebook(document=history).get_data()
  88. interpreter = get_api(request, snippet)
  89. if snippet.get('interface') == 'sqlalchemy':
  90. interpreter.options['session'] = session
  91. response['handle'] = interpreter.execute(notebook, snippet)
  92. # Retrieve and remove the result from the handle
  93. if response['handle'].get('sync'):
  94. result = response['handle'].pop('result')
  95. finally:
  96. if historify:
  97. _snippet = [s for s in notebook['snippets'] if s['id'] == snippet['id']][0]
  98. if 'handle' in response: # No failure
  99. _snippet['result']['handle'] = response['handle']
  100. _snippet['result']['statements_count'] = response['handle'].get('statements_count', 1)
  101. _snippet['result']['statement_id'] = response['handle'].get('statement_id', 0)
  102. _snippet['result']['handle']['statement'] = response['handle'].get('statement', snippet['statement']).strip() # For non HS2, as non multi query yet
  103. else:
  104. _snippet['status'] = 'failed'
  105. if history: # If _historify failed, history will be None. If we get Atomic block exception, something underneath interpreter.execute() crashed and is not handled.
  106. history.update_data(notebook)
  107. history.save()
  108. response['history_id'] = history.id
  109. response['history_uuid'] = history.uuid
  110. if notebook['isSaved']: # Keep track of history of saved queries
  111. response['history_parent_uuid'] = history.dependencies.filter(type__startswith='query-').latest('last_modified').uuid
  112. except QueryError, ex: # We inject the history information from _historify() to the failed queries
  113. if response.get('history_id'):
  114. ex.extra['history_id'] = response['history_id']
  115. if response.get('history_uuid'):
  116. ex.extra['history_uuid'] = response['history_uuid']
  117. if response.get('history_parent_uuid'):
  118. ex.extra['history_parent_uuid'] = response['history_parent_uuid']
  119. raise ex
  120. # Inject and HTML escape results
  121. if result is not None:
  122. response['result'] = result
  123. response['result']['data'] = escape_rows(result['data'])
  124. response['status'] = 0
  125. return response
  126. @require_POST
  127. @check_document_access_permission()
  128. @api_error_handler
  129. def execute(request, engine=None):
  130. notebook = json.loads(request.POST.get('notebook', '{}'))
  131. snippet = json.loads(request.POST.get('snippet', '{}'))
  132. response = _execute_notebook(request, notebook, snippet)
  133. return JsonResponse(response)
  134. @require_POST
  135. @check_document_access_permission()
  136. @api_error_handler
  137. def check_status(request):
  138. response = {'status': -1}
  139. notebook = json.loads(request.POST.get('notebook', '{}'))
  140. snippet = json.loads(request.POST.get('snippet', '{}'))
  141. if not snippet:
  142. nb_doc = Document2.objects.get_by_uuid(user=request.user, uuid=notebook['id'])
  143. notebook = Notebook(document=nb_doc).get_data()
  144. snippet = notebook['snippets'][0]
  145. try:
  146. response['query_status'] = get_api(request, snippet).check_status(notebook, snippet)
  147. response['status'] = 0
  148. except SessionExpired:
  149. response['status'] = 'expired'
  150. raise
  151. except QueryExpired:
  152. response['status'] = 'expired'
  153. raise
  154. finally:
  155. if response['status'] == 0 and snippet['status'] != response['query_status']:
  156. status = response['query_status']['status']
  157. elif response['status'] == 'expired':
  158. status = 'expired'
  159. else:
  160. status = 'failed'
  161. if notebook['type'].startswith('query') or notebook.get('isManaged'):
  162. nb_doc = Document2.objects.get(id=notebook['id'])
  163. if nb_doc.can_write(request.user):
  164. nb = Notebook(document=nb_doc).get_data()
  165. if status != nb['snippets'][0]['status']:
  166. nb['snippets'][0]['status'] = status
  167. nb_doc.update_data(nb)
  168. nb_doc.save()
  169. return JsonResponse(response)
  170. @require_POST
  171. @check_document_access_permission()
  172. @api_error_handler
  173. def fetch_result_data(request):
  174. response = {'status': -1}
  175. notebook = json.loads(request.POST.get('notebook', '{}'))
  176. snippet = json.loads(request.POST.get('snippet', '{}'))
  177. rows = json.loads(request.POST.get('rows', '100'))
  178. start_over = json.loads(request.POST.get('startOver', 'false'))
  179. response['result'] = get_api(request, snippet).fetch_result(notebook, snippet, rows, start_over)
  180. # Materialize and HTML escape results
  181. if response['result'].get('data') and response['result'].get('type') == 'table' and not response['result'].get('isEscaped'):
  182. response['result']['data'] = escape_rows(response['result']['data'])
  183. response['result']['isEscaped'] = True
  184. response['status'] = 0
  185. return JsonResponse(response)
  186. @require_POST
  187. @check_document_access_permission()
  188. @api_error_handler
  189. def fetch_result_metadata(request):
  190. response = {'status': -1}
  191. notebook = json.loads(request.POST.get('notebook', '{}'))
  192. snippet = json.loads(request.POST.get('snippet', '{}'))
  193. response['result'] = get_api(request, snippet).fetch_result_metadata(notebook, snippet)
  194. response['status'] = 0
  195. return JsonResponse(response)
  196. @require_POST
  197. @check_document_access_permission()
  198. @api_error_handler
  199. def fetch_result_size(request):
  200. response = {'status': -1}
  201. notebook = json.loads(request.POST.get('notebook', '{}'))
  202. snippet = json.loads(request.POST.get('snippet', '{}'))
  203. response['result'] = get_api(request, snippet).fetch_result_size(notebook, snippet)
  204. response['status'] = 0
  205. return JsonResponse(response)
  206. @require_POST
  207. @check_document_access_permission()
  208. @api_error_handler
  209. def cancel_statement(request):
  210. response = {'status': -1}
  211. notebook = json.loads(request.POST.get('notebook', '{}'))
  212. nb_doc = Document2.objects.get_by_uuid(user=request.user, uuid=notebook['uuid'])
  213. notebook = Notebook(document=nb_doc).get_data()
  214. snippet = notebook['snippets'][0]
  215. response['result'] = get_api(request, snippet).cancel(notebook, snippet)
  216. response['status'] = 0
  217. return JsonResponse(response)
  218. @require_POST
  219. @check_document_access_permission()
  220. @api_error_handler
  221. def get_logs(request):
  222. response = {'status': -1}
  223. notebook = json.loads(request.POST.get('notebook', '{}'))
  224. snippet = json.loads(request.POST.get('snippet', '{}'))
  225. startFrom = request.POST.get('from')
  226. startFrom = int(startFrom) if startFrom else None
  227. size = request.POST.get('size')
  228. size = int(size) if size else None
  229. db = get_api(request, snippet)
  230. full_log = smart_str(request.POST.get('full_log', ''))
  231. logs = smart_str(db.get_log(notebook, snippet, startFrom=startFrom, size=size))
  232. full_log += logs
  233. jobs = db.get_jobs(notebook, snippet, full_log)
  234. response['logs'] = logs.strip()
  235. response['progress'] = min(db.progress(notebook, snippet, logs=full_log), 99) if snippet['status'] != 'available' and snippet['status'] != 'success' else 100
  236. response['jobs'] = jobs
  237. response['isFullLogs'] = db.get_log_is_full_log(notebook, snippet)
  238. response['status'] = 0
  239. return JsonResponse(response)
  240. def _save_notebook(notebook, user):
  241. notebook_type = notebook.get('type', 'notebook')
  242. save_as = False
  243. if notebook.get('parentSavedQueryUuid'): # We save into the original saved query, not into the query history
  244. notebook_doc = Document2.objects.get_by_uuid(user=user, uuid=notebook['parentSavedQueryUuid'])
  245. elif notebook.get('id'):
  246. notebook_doc = Document2.objects.get(id=notebook['id'])
  247. else:
  248. notebook_doc = Document2.objects.create(name=notebook['name'], uuid=notebook['uuid'], type=notebook_type, owner=user)
  249. Document.objects.link(notebook_doc, owner=notebook_doc.owner, name=notebook_doc.name, description=notebook_doc.description, extra=notebook_type)
  250. save_as = True
  251. if notebook.get('directoryUuid'):
  252. notebook_doc.parent_directory = Document2.objects.get_by_uuid(user=user, uuid=notebook.get('directoryUuid'), perm_type='write')
  253. else:
  254. notebook_doc.parent_directory = Document2.objects.get_home_directory(user)
  255. notebook['isSaved'] = True
  256. notebook['isHistory'] = False
  257. notebook['id'] = notebook_doc.id
  258. _clear_sessions(notebook)
  259. notebook_doc1 = notebook_doc._get_doc1(doc2_type=notebook_type)
  260. notebook_doc.update_data(notebook)
  261. notebook_doc.search = _get_statement(notebook)
  262. notebook_doc.name = notebook_doc1.name = notebook['name']
  263. notebook_doc.description = notebook_doc1.description = notebook['description']
  264. notebook_doc.save()
  265. notebook_doc1.save()
  266. return notebook_doc, save_as
  267. @api_error_handler
  268. @require_POST
  269. @check_document_modify_permission()
  270. def save_notebook(request):
  271. response = {'status': -1}
  272. notebook = json.loads(request.POST.get('notebook', '{}'))
  273. notebook_doc, save_as = _save_notebook(notebook, request.user)
  274. response['status'] = 0
  275. response['save_as'] = save_as
  276. response.update(notebook_doc.to_dict())
  277. response['message'] = request.POST.get('editorMode') == 'true' and _('Query saved successfully') or _('Notebook saved successfully')
  278. return JsonResponse(response)
  279. def _clear_sessions(notebook):
  280. notebook['sessions'] = [_s for _s in notebook['sessions'] if _s['type'] in ('scala', 'spark', 'pyspark', 'sparkr', 'r')]
  281. def _historify(notebook, user):
  282. query_type = notebook['type']
  283. name = notebook['name'] if (notebook['name'] and notebook['name'].strip() != '') else DEFAULT_HISTORY_NAME
  284. is_managed = notebook.get('isManaged') == True # Prevents None
  285. if is_managed and Document2.objects.filter(uuid=notebook['uuid']).exists():
  286. history_doc = Document2.objects.get(uuid=notebook['uuid'])
  287. else:
  288. history_doc = Document2.objects.create(
  289. name=name,
  290. type=query_type,
  291. owner=user,
  292. is_history=True,
  293. is_managed=is_managed
  294. )
  295. # Link history of saved query
  296. if notebook['isSaved']:
  297. parent_doc = Document2.objects.get(uuid=notebook.get('parentSavedQueryUuid') or notebook['uuid']) # From previous history query or initial saved query
  298. notebook['parentSavedQueryUuid'] = parent_doc.uuid
  299. history_doc.dependencies.add(parent_doc)
  300. if not is_managed:
  301. Document.objects.link(
  302. history_doc,
  303. name=history_doc.name,
  304. owner=history_doc.owner,
  305. description=history_doc.description,
  306. extra=query_type
  307. )
  308. notebook['uuid'] = history_doc.uuid
  309. _clear_sessions(notebook)
  310. history_doc.update_data(notebook)
  311. history_doc.search = _get_statement(notebook)
  312. history_doc.save()
  313. return history_doc
  314. def _get_statement(notebook):
  315. if notebook['snippets'] and len(notebook['snippets']) > 0:
  316. return Notebook.statement_with_variables(notebook['snippets'][0])
  317. return ''
  318. @require_GET
  319. @api_error_handler
  320. @check_document_access_permission()
  321. def get_history(request):
  322. response = {'status': -1}
  323. doc_type = request.GET.get('doc_type')
  324. doc_text = request.GET.get('doc_text')
  325. page = min(int(request.GET.get('page', 1)), 100)
  326. limit = min(int(request.GET.get('limit', 50)), 100)
  327. is_notification_manager = request.GET.get('is_notification_manager', 'false') == 'true'
  328. if is_notification_manager:
  329. docs = Document2.objects.get_tasks_history(user=request.user)
  330. else:
  331. docs = Document2.objects.get_history(doc_type='query-%s' % doc_type, user=request.user)
  332. if doc_text:
  333. docs = docs.filter(Q(name__icontains=doc_text) | Q(description__icontains=doc_text) | Q(search__icontains=doc_text))
  334. # Paginate
  335. docs = docs.order_by('-last_modified')
  336. response['count'] = docs.count()
  337. docs = __paginate(page, limit, queryset=docs)['documents']
  338. history = []
  339. for doc in docs:
  340. notebook = Notebook(document=doc).get_data()
  341. if 'snippets' in notebook:
  342. statement = notebook['description'] if is_notification_manager else _get_statement(notebook)
  343. history.append({
  344. 'name': doc.name,
  345. 'id': doc.id,
  346. 'uuid': doc.uuid,
  347. 'type': doc.type,
  348. 'data': {
  349. 'statement': statement[:1001] if statement else '',
  350. 'lastExecuted': notebook['snippets'][0].get('lastExecuted', -1),
  351. 'status': notebook['snippets'][0]['status'],
  352. 'parentSavedQueryUuid': notebook.get('parentSavedQueryUuid', '')
  353. } if notebook['snippets'] else {},
  354. 'absoluteUrl': doc.get_absolute_url(),
  355. })
  356. else:
  357. LOG.error('Incomplete History Notebook: %s' % notebook)
  358. response['history'] = sorted(history, key=lambda row: row['data']['lastExecuted'], reverse=True)
  359. response['message'] = _('History fetched')
  360. response['status'] = 0
  361. return JsonResponse(response)
  362. @require_POST
  363. @api_error_handler
  364. @check_document_modify_permission()
  365. def clear_history(request):
  366. response = {'status': -1}
  367. notebook = json.loads(request.POST.get('notebook'), '{}')
  368. doc_type = request.POST.get('doc_type')
  369. is_notification_manager = request.POST.get('is_notification_manager', 'false') == 'true'
  370. if is_notification_manager:
  371. history = Document2.objects.get_tasks_history(user=request.user)
  372. else:
  373. history = Document2.objects.get_history(doc_type='query-%s' % doc_type, user=request.user)
  374. response['updated'] = history.delete()
  375. response['message'] = _('History cleared !')
  376. response['status'] = 0
  377. return JsonResponse(response)
  378. @require_GET
  379. @check_document_access_permission()
  380. def open_notebook(request):
  381. response = {'status': -1}
  382. notebook_id = request.GET.get('notebook')
  383. notebook = Notebook(document=Document2.objects.get(id=notebook_id))
  384. notebook = upgrade_session_properties(request, notebook)
  385. response['status'] = 0
  386. response['notebook'] = notebook.get_json()
  387. response['message'] = _('Notebook loaded successfully')
  388. @require_POST
  389. @check_document_access_permission()
  390. def close_notebook(request):
  391. response = {'status': -1, 'result': []}
  392. notebook = json.loads(request.POST.get('notebook', '{}'))
  393. for session in [_s for _s in notebook['sessions'] if _s['type'] in ('scala', 'spark', 'pyspark', 'sparkr', 'r')]:
  394. try:
  395. response['result'].append(get_api(request, session).close_session(session))
  396. except QueryExpired:
  397. pass
  398. except Exception, e:
  399. LOG.exception('Error closing session %s' % str(e))
  400. for snippet in [_s for _s in notebook['snippets'] if _s['type'] in ('hive', 'impala')]:
  401. try:
  402. if snippet['status'] != 'running':
  403. response['result'].append(get_api(request, snippet).close_statement(notebook, snippet))
  404. else:
  405. LOG.info('Not closing SQL snippet as still running.')
  406. except QueryExpired:
  407. pass
  408. except Exception, e:
  409. LOG.exception('Error closing statement %s' % str(e))
  410. response['status'] = 0
  411. response['message'] = _('Notebook closed successfully')
  412. return JsonResponse(response)
  413. @require_POST
  414. @check_document_access_permission()
  415. def close_statement(request):
  416. response = {'status': -1}
  417. # Passed by check_document_access_permission but unused by APIs
  418. notebook = json.loads(request.POST.get('notebook', '{}'))
  419. nb_doc = Document2.objects.get_by_uuid(user=request.user, uuid=notebook['uuid'])
  420. notebook = Notebook(document=nb_doc).get_data()
  421. snippet = notebook['snippets'][0]
  422. try:
  423. response['result'] = get_api(request, snippet).close_statement(notebook, snippet)
  424. except QueryExpired:
  425. pass
  426. response['status'] = 0
  427. response['message'] = _('Statement closed !')
  428. return JsonResponse(response)
  429. @require_POST
  430. @check_document_access_permission()
  431. @api_error_handler
  432. def autocomplete(request, server=None, database=None, table=None, column=None, nested=None):
  433. response = {'status': -1}
  434. # Passed by check_document_access_permission but unused by APIs
  435. notebook = json.loads(request.POST.get('notebook', '{}'))
  436. snippet = json.loads(request.POST.get('snippet', '{}'))
  437. try:
  438. autocomplete_data = get_api(request, snippet).autocomplete(snippet, database, table, column, nested)
  439. response.update(autocomplete_data)
  440. except QueryExpired:
  441. pass
  442. response['status'] = 0
  443. return JsonResponse(response)
  444. @require_POST
  445. @check_document_access_permission()
  446. @api_error_handler
  447. def get_sample_data(request, server=None, database=None, table=None, column=None):
  448. response = {'status': -1}
  449. # Passed by check_document_access_permission but unused by APIs
  450. notebook = json.loads(request.POST.get('notebook', '{}'))
  451. snippet = json.loads(request.POST.get('snippet', '{}'))
  452. async = json.loads(request.POST.get('async', 'false'))
  453. operation = json.loads(request.POST.get('operation', '"default"'))
  454. sample_data = get_api(request, snippet).get_sample_data(snippet, database, table, column, async=async, operation=operation)
  455. response.update(sample_data)
  456. response['status'] = 0
  457. return JsonResponse(response)
  458. @require_POST
  459. @check_document_access_permission()
  460. @api_error_handler
  461. def explain(request):
  462. response = {'status': -1}
  463. notebook = json.loads(request.POST.get('notebook', '{}'))
  464. snippet = json.loads(request.POST.get('snippet', '{}'))
  465. response = get_api(request, snippet).explain(notebook, snippet)
  466. return JsonResponse(response)
  467. @require_POST
  468. @api_error_handler
  469. def format(request):
  470. response = {'status': 0}
  471. statements = request.POST.get('statements', '')
  472. response['formatted_statements'] = sqlparse.format(statements, reindent=True, keyword_case='upper') # SQL only currently
  473. return JsonResponse(response)
  474. @require_POST
  475. @check_document_access_permission()
  476. @api_error_handler
  477. def export_result(request):
  478. response = {'status': -1, 'message': _('Success')}
  479. # Passed by check_document_access_permission but unused by APIs
  480. notebook = json.loads(request.POST.get('notebook', '{}'))
  481. snippet = json.loads(request.POST.get('snippet', '{}'))
  482. data_format = json.loads(request.POST.get('format', '"hdfs-file"'))
  483. destination = urllib.unquote(json.loads(request.POST.get('destination', '""')))
  484. overwrite = json.loads(request.POST.get('overwrite', 'false'))
  485. is_embedded = json.loads(request.POST.get('is_embedded', 'false'))
  486. start_time = json.loads(request.POST.get('start_time', '-1'))
  487. api = get_api(request, snippet)
  488. if data_format == 'hdfs-file': # Blocking operation, like downloading
  489. if request.fs.isdir(destination):
  490. if notebook.get('name'):
  491. destination += '/%(name)s.csv' % notebook
  492. else:
  493. destination += '/%(type)s-%(id)s.csv' % notebook
  494. if overwrite and request.fs.exists(destination):
  495. request.fs.do_as_user(request.user.username, request.fs.rmtree, destination)
  496. response['watch_url'] = api.export_data_as_hdfs_file(snippet, destination, overwrite)
  497. response['status'] = 0
  498. request.audit = {
  499. 'operation': 'EXPORT',
  500. 'operationText': 'User %s exported to HDFS destination: %s' % (request.user.username, destination),
  501. 'allowed': True
  502. }
  503. elif data_format == 'hive-table':
  504. if is_embedded:
  505. sql, success_url = api.export_data_as_table(notebook, snippet, destination)
  506. task = make_notebook(
  507. name=_('Export %s query to table %s') % (snippet['type'], destination),
  508. description=_('Query %s to %s') % (_get_snippet_name(notebook), success_url),
  509. editor_type=snippet['type'],
  510. statement=sql,
  511. status='ready',
  512. database=snippet['database'],
  513. on_success_url=success_url,
  514. last_executed=start_time,
  515. is_task=True
  516. )
  517. response = task.execute(request)
  518. else:
  519. notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
  520. response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=save_as_table&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
  521. response['status'] = 0
  522. request.audit = {
  523. 'operation': 'EXPORT',
  524. 'operationText': 'User %s exported to Hive table: %s' % (request.user.username, destination),
  525. 'allowed': True
  526. }
  527. elif data_format == 'hdfs-directory':
  528. if is_embedded:
  529. sql, success_url = api.export_large_data_to_hdfs(notebook, snippet, destination)
  530. task = make_notebook(
  531. name=_('Export %s query to directory') % snippet['type'],
  532. description=_('Query %s to %s') % (_get_snippet_name(notebook), success_url),
  533. editor_type=snippet['type'],
  534. statement=sql,
  535. status='ready-execute',
  536. database=snippet['database'],
  537. on_success_url=success_url,
  538. last_executed=start_time,
  539. is_task=True
  540. )
  541. response = task.execute(request)
  542. else:
  543. notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
  544. response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=insert_as_query&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
  545. response['status'] = 0
  546. request.audit = {
  547. 'operation': 'EXPORT',
  548. 'operationText': 'User %s exported to HDFS directory: %s' % (request.user.username, destination),
  549. 'allowed': True
  550. }
  551. elif data_format in ('search-index', 'dashboard'):
  552. # Open the result in the Dashboard via a SQL sub-query or the Import wizard (quick vs scalable)
  553. if is_embedded:
  554. notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
  555. if data_format == 'dashboard':
  556. engine = notebook['type'].replace('query-', '')
  557. response['watch_url'] = reverse('dashboard:browse', kwargs={'name': notebook_id}) + '?source=query&engine=%(engine)s' % {'engine': engine}
  558. response['status'] = 0
  559. else:
  560. sample = get_api(request, snippet).fetch_result(notebook, snippet, rows=4, start_over=True)
  561. for col in sample['meta']:
  562. col['type'] = HiveFormat.FIELD_TYPE_TRANSLATE.get(col['type'], 'string')
  563. response['status'] = 0
  564. response['id'] = notebook_id
  565. response['name'] = _get_snippet_name(notebook)
  566. response['source_type'] = 'query'
  567. response['target_type'] = 'index'
  568. response['target_path'] = destination
  569. response['sample'] = list(sample['data'])
  570. response['columns'] = [
  571. Field(col['name'], col['type']).to_dict() for col in sample['meta']
  572. ]
  573. else:
  574. notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
  575. response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=index_query&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
  576. response['status'] = 0
  577. if response.get('status') != 0:
  578. response['message'] = _('Exporting result failed.')
  579. return JsonResponse(response)
  580. @require_POST
  581. @check_document_access_permission()
  582. @api_error_handler
  583. def statement_risk(request):
  584. response = {'status': -1, 'message': ''}
  585. notebook = json.loads(request.POST.get('notebook', '{}'))
  586. snippet = json.loads(request.POST.get('snippet', '{}'))
  587. api = HS2Api(request.user, snippet)
  588. response['query_complexity'] = api.statement_risk(notebook, snippet)
  589. response['status'] = 0
  590. return JsonResponse(response)
  591. @require_POST
  592. @check_document_access_permission()
  593. @api_error_handler
  594. def statement_compatibility(request):
  595. response = {'status': -1, 'message': ''}
  596. notebook = json.loads(request.POST.get('notebook', '{}'))
  597. snippet = json.loads(request.POST.get('snippet', '{}'))
  598. source_platform = request.POST.get('sourcePlatform')
  599. target_platform = request.POST.get('targetPlatform')
  600. api = get_api(request, snippet)
  601. response['query_compatibility'] = api.statement_compatibility(notebook, snippet, source_platform=source_platform, target_platform=target_platform)
  602. response['status'] = 0
  603. return JsonResponse(response)
  604. @require_POST
  605. @check_document_access_permission()
  606. @api_error_handler
  607. def statement_similarity(request):
  608. response = {'status': -1, 'message': ''}
  609. notebook = json.loads(request.POST.get('notebook', '{}'))
  610. snippet = json.loads(request.POST.get('snippet', '{}'))
  611. source_platform = request.POST.get('sourcePlatform')
  612. api = get_api(request, snippet)
  613. response['statement_similarity'] = api.statement_similarity(notebook, snippet, source_platform=source_platform)
  614. response['status'] = 0
  615. return JsonResponse(response)
  616. @require_POST
  617. @check_document_access_permission()
  618. @api_error_handler
  619. def get_external_statement(request):
  620. response = {'status': -1, 'message': ''}
  621. notebook = json.loads(request.POST.get('notebook', '{}'))
  622. snippet = json.loads(request.POST.get('snippet', '{}'))
  623. if snippet.get('statementType') == 'file':
  624. response['statement'] = _get_statement_from_file(request.user, request.fs, snippet)
  625. elif snippet.get('statementType') == 'document':
  626. notebook = Notebook(Document2.objects.get_by_uuid(user=request.user, uuid=snippet['associatedDocumentUuid'], perm_type='read'))
  627. response['statement'] = notebook.get_str()
  628. response['status'] = 0
  629. return JsonResponse(response)
  630. def _get_statement_from_file(user, fs, snippet):
  631. script_path = snippet['statementPath']
  632. if script_path:
  633. script_path = script_path.replace('hdfs://', '')
  634. if fs.do_as_user(user, fs.isfile, script_path):
  635. return fs.do_as_user(user, fs.read, script_path, 0, 16 * 1024 ** 2)
  636. @require_POST
  637. @api_error_handler
  638. def describe(request, database, table=None, column=None):
  639. response = {'status': -1, 'message': ''}
  640. notebook = json.loads(request.POST.get('notebook', '{}'))
  641. source_type = request.POST.get('source_type', '')
  642. snippet = {'type': source_type}
  643. describe = get_api(request, snippet).describe(notebook, snippet, database, table, column=column)
  644. response.update(describe)
  645. return JsonResponse(response)