views.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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 StringIO
  18. import json
  19. import logging
  20. import os
  21. import re
  22. import socket
  23. import sys
  24. import tempfile
  25. import time
  26. import traceback
  27. import zipfile
  28. import validate
  29. from django.conf import settings
  30. from django.shortcuts import render_to_response
  31. from django.http import HttpResponse
  32. from django.urls import reverse
  33. from wsgiref.util import FileWrapper
  34. from django.shortcuts import redirect
  35. from django.utils.translation import ugettext as _
  36. from django.views.decorators.http import require_POST
  37. from configobj import ConfigObj, get_extra_values, ConfigObjError
  38. import django.views.debug
  39. from aws.conf import is_enabled as is_s3_enabled, has_s3_access
  40. from azure.conf import is_adls_enabled, has_adls_access
  41. import desktop.conf
  42. import desktop.log.log_buffer
  43. from desktop import appmanager
  44. from desktop.api import massaged_tags_for_json, massaged_documents_for_json, _get_docs
  45. from desktop.conf import USE_NEW_EDITOR, IS_HUE_4, HUE_LOAD_BALANCER, get_clusters, DISABLE_HUE_3
  46. from desktop.lib import django_mako
  47. from desktop.lib.conf import GLOBAL_CONFIG, BoundConfig, _configs_from_dir
  48. from desktop.lib.config_spec_dump import ConfigSpec
  49. from desktop.lib.django_util import JsonResponse, login_notrequired, render
  50. from desktop.lib.i18n import smart_str
  51. from desktop.lib.paths import get_desktop_root
  52. from desktop.lib.thread_util import dump_traceback
  53. from desktop.log.access import access_log_level, access_warn, AccessInfo
  54. from desktop.log import set_all_debug as _set_all_debug, reset_all_debug as _reset_all_debug, get_all_debug as _get_all_debug
  55. from desktop.models import Settings, hue_version, _get_apps, UserPreferences
  56. from desktop.auth.backend import is_admin
  57. LOG = logging.getLogger(__name__)
  58. def is_alive(request):
  59. return HttpResponse('')
  60. def hue(request):
  61. current_app, other_apps, apps_list = _get_apps(request.user, '')
  62. clusters = get_clusters(request.user).values()
  63. return render('hue.mako', request, {
  64. 'apps': apps_list,
  65. 'other_apps': other_apps,
  66. 'is_s3_enabled': is_s3_enabled() and has_s3_access(request.user),
  67. 'is_adls_enabled': is_adls_enabled() and has_adls_access(request.user),
  68. 'is_ldap_setup': 'desktop.auth.backend.LdapBackend' in desktop.conf.AUTH.BACKEND.get(),
  69. 'leaflet': {
  70. 'layer': desktop.conf.LEAFLET_TILE_LAYER.get(),
  71. 'attribution': desktop.conf.LEAFLET_TILE_LAYER_ATTRIBUTION.get(),
  72. 'map_options': json.dumps(desktop.conf.LEAFLET_MAP_OPTIONS.get()),
  73. 'layer_options': json.dumps(desktop.conf.LEAFLET_TILE_LAYER_OPTIONS.get()),
  74. },
  75. 'is_demo': desktop.conf.DEMO_ENABLED.get(),
  76. 'banner_message': get_banner_message(request),
  77. 'user_preferences': dict((x.key, x.value) for x in UserPreferences.objects.filter(user=request.user)),
  78. 'cluster': clusters[0]['type'] if clusters else None
  79. })
  80. def ko_editor(request):
  81. apps = appmanager.get_apps_dict(request.user)
  82. return render('ko_editor.mako', request, {
  83. 'apps': apps,
  84. })
  85. def ko_metastore(request):
  86. apps = appmanager.get_apps_dict(request.user)
  87. return render('ko_metastore.mako', request, {
  88. 'apps': apps,
  89. })
  90. def home(request):
  91. docs = _get_docs(request.user)
  92. apps = appmanager.get_apps_dict(request.user)
  93. return render('home.mako', request, {
  94. 'apps': apps,
  95. 'json_documents': json.dumps(massaged_documents_for_json(docs, request.user)),
  96. 'json_tags': json.dumps(massaged_tags_for_json(docs, request.user)),
  97. })
  98. def home2(request, is_embeddable=False):
  99. apps = appmanager.get_apps_dict(request.user)
  100. return render('home2.mako', request, {
  101. 'apps': apps,
  102. 'is_embeddable': request.GET.get('is_embeddable', False)
  103. })
  104. def catalog(request, is_embeddable=False):
  105. apps = appmanager.get_apps_dict(request.user)
  106. return render('catalog.mako', request, {
  107. 'apps': apps,
  108. 'is_embeddable': request.GET.get('is_embeddable', False)
  109. })
  110. def home_embeddable(request):
  111. return home2(request, True)
  112. def not_found(request):
  113. return render('404.mako', request, {
  114. 'is_embeddable': request.GET.get('is_embeddable', False)
  115. })
  116. def server_error(request):
  117. return render('500.mako', request, {
  118. 'is_embeddable': request.GET.get('is_embeddable', False)
  119. })
  120. def path_forbidden(request):
  121. return render('403.mako', request, {
  122. 'is_embeddable': request.GET.get('is_embeddable', False)
  123. })
  124. def log_js_error(request):
  125. ai = AccessInfo(request)
  126. ai.log(level=logging.ERROR, msg='JS ERROR: ' + request.POST.get('jserror', 'Unspecified JS error'))
  127. return JsonResponse({'status': 0})
  128. def log_analytics(request):
  129. ai = AccessInfo(request)
  130. ai.log(level=logging.INFO, msg='PAGE: ' + request.POST.get('page'))
  131. return JsonResponse({'status': 0})
  132. @access_log_level(logging.WARN)
  133. def log_view(request):
  134. """
  135. We have a log handler that retains the last X characters of log messages.
  136. If it is attached to the root logger, this view will display that history,
  137. otherwise it will report that it can't be found.
  138. """
  139. if not is_admin(request.user):
  140. return HttpResponse(_("You must be a superuser."))
  141. hostname = socket.gethostname()
  142. l = logging.getLogger()
  143. for h in l.handlers:
  144. if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
  145. return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get("q", ""), hostname=hostname, is_embeddable=request.GET.get('is_embeddable', False)))
  146. return render('logs.mako', request, dict(log=[_("No logs found!")], query='', hostname=hostname, is_embeddable=request.GET.get('is_embeddable', False)))
  147. @access_log_level(logging.WARN)
  148. def download_log_view(request):
  149. """
  150. Zip up the log buffer and then return as a file attachment.
  151. """
  152. if not is_admin(request.user):
  153. return HttpResponse(_("You must be a superuser."))
  154. l = logging.getLogger()
  155. for h in l.handlers:
  156. if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
  157. try:
  158. # We want to avoid doing a '\n'.join of the entire log in memory
  159. # in case it is rather big. So we write it to a file line by line
  160. # and pass that file to zipfile, which might follow a more efficient path.
  161. tmp = tempfile.NamedTemporaryFile()
  162. log_tmp = tempfile.NamedTemporaryFile("w+t")
  163. for l in h.buf:
  164. log_tmp.write(smart_str(l, errors='replace') + '\n')
  165. # This is not just for show - w/out flush, we often get truncated logs
  166. log_tmp.flush()
  167. t = time.time()
  168. zip = zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED)
  169. zip.write(log_tmp.name, "hue-logs/hue-%s.log" % t)
  170. zip.close()
  171. length = tmp.tell()
  172. # if we don't seek to start of file, no bytes will be written
  173. tmp.seek(0)
  174. wrapper = FileWrapper(tmp)
  175. response = HttpResponse(wrapper, content_type="application/zip")
  176. response['Content-Disposition'] = 'attachment; filename=hue-logs-%s.zip' % t
  177. response['Content-Length'] = length
  178. return response
  179. except Exception, e:
  180. LOG.exception("Couldn't construct zip file to write logs")
  181. return log_view(request)
  182. return render_to_response("logs.mako", dict(log=[_("No logs found.")], is_embeddable=request.GET.get('is_embeddable', False)))
  183. def bootstrap(request):
  184. """Concatenates bootstrap.js files from all installed Hue apps."""
  185. # Has some None's for apps that don't have bootsraps.
  186. all_bootstraps = [(app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name)]
  187. # Iterator over the streams.
  188. concatenated = ["\n/* %s */\n%s" % (app.name, b.read()) for app, b in all_bootstraps if b is not None]
  189. # HttpResponse can take an iteratable as the first argument, which
  190. # is what happens here.
  191. return HttpResponse(concatenated, content_type='text/javascript')
  192. _status_bar_views = []
  193. def register_status_bar_view(view):
  194. global _status_bar_views
  195. _status_bar_views.append(view)
  196. @access_log_level(logging.DEBUG)
  197. def status_bar(request):
  198. """
  199. Concatenates multiple views together to build up a "status bar"/"status_bar".
  200. These views are registered using register_status_bar_view above.
  201. """
  202. resp = ""
  203. for view in _status_bar_views:
  204. try:
  205. r = view(request)
  206. if r and r.status_code == 200:
  207. resp += r.content
  208. else:
  209. LOG.warning("Failed to execute status_bar view %s" % (view,))
  210. except:
  211. LOG.exception("Failed to execute status_bar view %s" % (view,))
  212. return HttpResponse(resp)
  213. def dump_config(request):
  214. # Note that this requires login (as do most apps).
  215. show_private = False
  216. conf_dir = os.path.realpath(os.getenv("HUE_CONF_DIR", get_desktop_root("conf")))
  217. if not is_admin(request.user):
  218. return HttpResponse(_("You must be a superuser."))
  219. if request.GET.get("private"):
  220. show_private = True
  221. apps = sorted(appmanager.DESKTOP_MODULES, key=lambda app: app.name)
  222. apps_names = [app.name for app in apps]
  223. top_level = sorted(GLOBAL_CONFIG.get().values(), key=lambda obj: apps_names.index(obj.config.key))
  224. return render("dump_config.mako", request, dict(
  225. show_private=show_private,
  226. top_level=top_level,
  227. conf_dir=conf_dir,
  228. is_embeddable=request.GET.get('is_embeddable', False),
  229. apps=apps))
  230. @access_log_level(logging.WARN)
  231. def threads(request):
  232. """Dumps out server threads. Useful for debugging."""
  233. out = StringIO.StringIO()
  234. dump_traceback(file=out)
  235. if not is_admin(request.user):
  236. return HttpResponse(_("You must be a superuser."))
  237. if request.is_ajax():
  238. return HttpResponse(out.getvalue(), content_type="text/plain")
  239. else:
  240. return render("threads.mako", request, {'text': out.getvalue(), 'is_embeddable': request.GET.get('is_embeddable', False)})
  241. @access_log_level(logging.WARN)
  242. def memory(request):
  243. """Dumps out server threads. Useful for debugging."""
  244. if not is_admin(request.user):
  245. return HttpResponse(_("You must be a superuser."))
  246. if not hasattr(settings, 'MEMORY_PROFILER'):
  247. return HttpResponse(_("You must enable the memory profiler via the memory_profiler config in the hue.ini."))
  248. # type, from, to, index
  249. command_order = {
  250. 'type': 0,
  251. 'from': 1,
  252. 'to': 2,
  253. 'index': 3
  254. }
  255. default_command = [None, None, None, None]
  256. commands = []
  257. for item in request.GET:
  258. res = re.match(r'(?P<command>\w+)\.(?P<count>\d+)', item)
  259. if res:
  260. d = res.groupdict()
  261. count = int(d['count'])
  262. command = str(d['command'])
  263. while len(commands) <= count:
  264. commands.append(default_command[:])
  265. commands[count][command_order.get(command)] = request.GET.get(item)
  266. heap = settings.MEMORY_PROFILER.heap()
  267. for command in commands:
  268. if command[0] is not None:
  269. heap = getattr(heap, command[0])
  270. if command[1] is not None and command[2] is not None:
  271. heap = heap[int(command[1]):int(command[2])]
  272. if command[3] is not None:
  273. heap = heap[int(command[3])]
  274. return HttpResponse(str(heap), content_type="text/plain")
  275. @login_notrequired
  276. def jasmine(request):
  277. return render('jasmine.mako', request, None)
  278. def global_js_constants(request):
  279. return HttpResponse(render('global_js_constants.mako', request, {
  280. 'is_s3_enabled': is_s3_enabled() and has_s3_access(request.user),
  281. 'leaflet': {
  282. 'layer': desktop.conf.LEAFLET_TILE_LAYER.get(),
  283. 'attribution': desktop.conf.LEAFLET_TILE_LAYER_ATTRIBUTION.get(),
  284. 'map_options': json.dumps(desktop.conf.LEAFLET_MAP_OPTIONS.get()),
  285. 'layer_options': json.dumps(desktop.conf.LEAFLET_TILE_LAYER_OPTIONS.get()),
  286. }
  287. }), content_type="application/javascript")
  288. def ace_sql_location_worker(request):
  289. return HttpResponse(render('ace_sql_location_worker.mako', request, None), content_type="application/javascript")
  290. def ace_sql_syntax_worker(request):
  291. return HttpResponse(render('ace_sql_syntax_worker.mako', request, None), content_type="application/javascript")
  292. def assist_m(request):
  293. return render('assist_m.mako', request, None)
  294. @login_notrequired
  295. def unsupported(request):
  296. return render('unsupported.mako', request, None)
  297. def index(request):
  298. is_hue_4 = IS_HUE_4.get() or DISABLE_HUE_3.get()
  299. if is_hue_4:
  300. try:
  301. user_hue_version = json.loads(UserPreferences.objects.get(user=request.user, key='hue_version').value)
  302. is_hue_4 = user_hue_version >= 4 or DISABLE_HUE_3.get()
  303. except UserPreferences.DoesNotExist:
  304. pass
  305. if is_admin(request.user) and request.COOKIES.get('hueLandingPage') != 'home' and not IS_HUE_4.get():
  306. return redirect(reverse('about:index'))
  307. else:
  308. if is_hue_4:
  309. return redirect('desktop_views_hue')
  310. elif USE_NEW_EDITOR.get():
  311. return redirect('desktop_views_home2')
  312. else:
  313. return home(request)
  314. def csrf_failure(request, reason=None):
  315. """Registered handler for CSRF."""
  316. access_warn(request, reason)
  317. return render("403_csrf.mako", request, dict(uri=request.build_absolute_uri()), status=403)
  318. def serve_403_error(request, *args, **kwargs):
  319. """Registered handler for 403. We just return a simple error"""
  320. access_warn(request, "403 access forbidden")
  321. return render("403.mako", request, dict(uri=request.build_absolute_uri()), status=403)
  322. def serve_404_error(request, *args, **kwargs):
  323. """Registered handler for 404. We just return a simple error"""
  324. access_warn(request, "404 not found")
  325. return render("404.mako", request, dict(uri=request.build_absolute_uri()), status=404)
  326. def serve_500_error(request, *args, **kwargs):
  327. """Registered handler for 500. We use the debug view to make debugging easier."""
  328. try:
  329. exc_info = sys.exc_info()
  330. if exc_info:
  331. if desktop.conf.HTTP_500_DEBUG_MODE.get() and exc_info[0] and exc_info[1]:
  332. # If (None, None, None), default server error describing why this failed.
  333. return django.views.debug.technical_500_response(request, *exc_info)
  334. else:
  335. # Could have an empty traceback
  336. return render("500.mako", request, {'traceback': traceback.extract_tb(exc_info[2])})
  337. else:
  338. # exc_info could be empty
  339. return render("500.mako", request, {})
  340. finally:
  341. # Fallback to default 500 response if ours fails
  342. # Will end up here:
  343. # - Middleware or authentication backends problems
  344. # - Certain missing imports
  345. # - Packaging and install issues
  346. pass
  347. _LOG_LEVELS = {
  348. "critical": logging.CRITICAL,
  349. "error": logging.ERROR,
  350. "warning": logging.WARNING,
  351. "info": logging.INFO,
  352. "debug": logging.DEBUG
  353. }
  354. _MAX_LOG_FRONTEND_EVENT_LENGTH = 1024
  355. _LOG_FRONTEND_LOGGER = logging.getLogger("desktop.views.log_frontend_event")
  356. @login_notrequired
  357. def log_frontend_event(request):
  358. """
  359. Logs arguments to server's log. Returns an
  360. empty string.
  361. Parameters (specified via either GET or POST) are
  362. "logname", "level" (one of "debug", "info", "warning",
  363. "error", or "critical"), and "message".
  364. """
  365. def get(param, default=None):
  366. return request.GET.get(param, default)
  367. level = _LOG_LEVELS.get(get("level"), logging.INFO)
  368. msg = "Untrusted log event from user %s: %s" % (
  369. request.user,
  370. get("message", "")[:_MAX_LOG_FRONTEND_EVENT_LENGTH])
  371. _LOG_FRONTEND_LOGGER.log(level, msg)
  372. return HttpResponse("")
  373. def commonheader_m(title, section, user, request=None, padding="90px", skip_topbar=False, skip_idle_timeout=False):
  374. return commonheader(title, section, user, request, padding, skip_topbar, skip_idle_timeout, True)
  375. def commonheader(title, section, user, request=None, padding="90px", skip_topbar=False, skip_idle_timeout=False, is_mobile=False):
  376. """
  377. Returns the rendered common header
  378. """
  379. current_app, other_apps, apps_list = _get_apps(user, section)
  380. template = 'common_header.mako'
  381. if is_mobile:
  382. template = 'common_header_m.mako'
  383. return django_mako.render_to_string(template, {
  384. 'current_app': current_app,
  385. 'apps': apps_list,
  386. 'other_apps': other_apps,
  387. 'title': title,
  388. 'section': section,
  389. 'padding': padding,
  390. 'user': user,
  391. 'request': request,
  392. 'skip_topbar': skip_topbar,
  393. 'skip_idle_timeout': skip_idle_timeout,
  394. 'leaflet': {
  395. 'layer': desktop.conf.LEAFLET_TILE_LAYER.get(),
  396. 'attribution': desktop.conf.LEAFLET_TILE_LAYER_ATTRIBUTION.get(),
  397. 'map_options': json.dumps(desktop.conf.LEAFLET_MAP_OPTIONS.get()),
  398. 'layer_options': json.dumps(desktop.conf.LEAFLET_TILE_LAYER_OPTIONS.get()),
  399. },
  400. 'is_demo': desktop.conf.DEMO_ENABLED.get(),
  401. 'is_ldap_setup': 'desktop.auth.backend.LdapBackend' in desktop.conf.AUTH.BACKEND.get(),
  402. 'is_s3_enabled': is_s3_enabled() and has_s3_access(user),
  403. 'is_adls_enabled': is_adls_enabled() and has_adls_access(request.user),
  404. 'banner_message': get_banner_message(request)
  405. })
  406. def get_banner_message(request):
  407. banner_message = None
  408. forwarded_host = request.get_host()
  409. message = None
  410. path_info = request.environ.get("PATH_INFO")
  411. if IS_HUE_4.get() and path_info.find("/hue/") < 0 and path_info.find("accounts/login") < 0:
  412. url = request.build_absolute_uri("/hue")
  413. link = '<a href="%s" style="color: #FFF; font-weight: bold">%s</a>' % (url, url)
  414. message = _('You are accessing an older version of Hue, please switch to the latest version: %s.') % link
  415. LOG.warn('User %s is using Hue 3 UI' % request.user.username)
  416. if HUE_LOAD_BALANCER.get() and HUE_LOAD_BALANCER.get() != [''] and \
  417. (not forwarded_host or not any(forwarded_host in lb for lb in HUE_LOAD_BALANCER.get())):
  418. message = _('You are accessing a non-optimized Hue, please switch to one of the available addresses: %s') % \
  419. (", ".join(['<a href="%s" style="color: #FFF; font-weight: bold">%s</a>' % (host, host) for host in HUE_LOAD_BALANCER.get()]))
  420. LOG.warn('User %s is bypassing the load balancer' % request.user.username)
  421. if message:
  422. banner_message = '<div style="padding: 4px; text-align: center; background-color: #003F6C; height: 24px; color: #DBE8F1">%s</div>' % message
  423. return banner_message
  424. def commonshare():
  425. return django_mako.render_to_string("common_share.mako", {})
  426. def commonshare2():
  427. return django_mako.render_to_string("common_share2.mako", {})
  428. def commonimportexport(request):
  429. return django_mako.render_to_string("common_import_export.mako", {'request': request})
  430. def login_modal(request):
  431. return desktop.auth.views.dt_login(request, True)
  432. def is_idle(request):
  433. return HttpResponse("no!")
  434. def commonfooter_m(request, messages=None):
  435. return commonfooter(request, messages, True)
  436. def commonfooter(request, messages=None, is_mobile=False):
  437. """
  438. Returns the rendered common footer
  439. """
  440. if messages is None:
  441. messages = {}
  442. hue_settings = Settings.get_settings()
  443. template = 'common_footer.mako'
  444. if is_mobile:
  445. template = 'common_footer_m.mako'
  446. return django_mako.render_to_string(template, {
  447. 'request': request,
  448. 'messages': messages,
  449. 'version': hue_version(),
  450. 'collect_usage': collect_usage(),
  451. })
  452. def collect_usage():
  453. return desktop.conf.COLLECT_USAGE.get() and Settings.get_settings().collect_usage
  454. # If the app's conf.py has a config_validator() method, call it.
  455. CONFIG_VALIDATOR = 'config_validator'
  456. #
  457. # Cache config errors because (1) they mostly don't go away until restart,
  458. # and (2) they can be costly to compute. So don't stress the system just because
  459. # the dock bar wants to refresh every n seconds.
  460. #
  461. # The actual viewing of all errors may choose to disregard the cache.
  462. #
  463. _CONFIG_ERROR_LIST = None
  464. def _get_config_errors(request, cache=True):
  465. """Returns a list of (confvar, err_msg) tuples."""
  466. global _CONFIG_ERROR_LIST
  467. if not cache or _CONFIG_ERROR_LIST is None:
  468. error_list = [ ]
  469. for module in appmanager.DESKTOP_MODULES:
  470. # Get the config_validator() function
  471. try:
  472. validator = getattr(module.conf, CONFIG_VALIDATOR)
  473. except AttributeError:
  474. continue
  475. if not callable(validator):
  476. LOG.warn("Auto config validation: %s.%s is not a function" %
  477. (module.conf.__name__, CONFIG_VALIDATOR))
  478. continue
  479. try:
  480. for confvar, error in validator(request.user):
  481. error = {
  482. 'name': confvar if isinstance(confvar, str) else confvar.get_fully_qualifying_key(),
  483. 'message': error,
  484. }
  485. if isinstance(confvar, BoundConfig):
  486. error['value'] = confvar.get()
  487. error_list.append(error)
  488. except Exception, ex:
  489. LOG.exception("Error in config validation by %s: %s" % (module.nice_name, ex))
  490. validate_by_spec(error_list)
  491. _CONFIG_ERROR_LIST = error_list
  492. if _CONFIG_ERROR_LIST:
  493. LOG.warn("Errors in config : %s" % _CONFIG_ERROR_LIST)
  494. return _CONFIG_ERROR_LIST
  495. def validate_by_spec(error_list):
  496. try:
  497. # Generate the spec file
  498. configspec = generate_configspec()
  499. config_dir = os.getenv("HUE_CONF_DIR", get_desktop_root("conf"))
  500. # Load the .ini files
  501. conf = load_confs(configspec.name, _configs_from_dir(config_dir))
  502. # Validate after merging all the confs
  503. collect_validation_messages(conf, error_list)
  504. finally:
  505. os.remove(configspec.name)
  506. def load_confs(configspecpath, conf_source=None):
  507. """Loads and merges all of the configurations passed in,
  508. returning a ConfigObj for the result.
  509. @param conf_source if not specified, reads conf/ from
  510. desktop/conf/. Otherwise should be a generator
  511. of ConfigObjs
  512. """
  513. if conf_source is None:
  514. conf_source = _configs_from_dir(get_desktop_root("conf"))
  515. conf = ConfigObj(configspec=configspecpath)
  516. for in_conf in conf_source:
  517. conf.merge(in_conf)
  518. return conf
  519. def generate_configspec():
  520. configspec = tempfile.NamedTemporaryFile(delete=False)
  521. cs = ConfigSpec(configspec)
  522. cs.generate()
  523. return configspec
  524. def collect_validation_messages(conf, error_list):
  525. validator = validate.Validator()
  526. conf.validate(validator, preserve_errors=True)
  527. message = []
  528. cm_extras = {
  529. 'hadoop_hdfs_home': [('hadoop', 'hdfs_clusters', 'default')],
  530. 'hadoop_bin': [('hadoop', 'hdfs_clusters', 'default'), ('hadoop', 'yarn_clusters', 'default'), ('hadoop', 'yarn_clusters', 'ha')],
  531. 'hadoop_mapred_home': [('hadoop', 'yarn_clusters', 'default'), ('hadoop', 'yarn_clusters', 'ha')],
  532. 'hadoop_conf_dir': [('hadoop', 'yarn_clusters', 'default'), ('hadoop', 'yarn_clusters', 'ha')],
  533. 'ssl_cacerts': [('beeswax', 'ssl'), ('impala', 'ssl')],
  534. 'remote_data_dir': [('liboozie', )],
  535. 'shell': [()]
  536. }
  537. whitelist_extras = ((sections, name) for sections, name in get_extra_values(conf) if not (name in desktop.conf.APP_BLACKLIST.get() or (name in cm_extras.keys() and sections in cm_extras[name])))
  538. for sections, name in whitelist_extras:
  539. the_section = conf
  540. hierarchy_sections_string = ''
  541. try:
  542. parent = conf
  543. for section in sections:
  544. the_section = parent[section]
  545. hierarchy_sections_string += "[" * the_section.depth + section + "]" * the_section.depth + " "
  546. parent = the_section
  547. except KeyError, ex:
  548. LOG.warn("Section %s not found: %s" % (section, str(ex)))
  549. the_value = ''
  550. try:
  551. # the_value may be a section or a value
  552. the_value = the_section[name]
  553. except KeyError, ex:
  554. LOG.warn("Error in accessing Section or Value %s: %s" % (name, str(ex)))
  555. section_or_value = 'keyvalue'
  556. if isinstance(the_value, dict):
  557. # Sections are subclasses of dict
  558. section_or_value = 'section'
  559. section_string = hierarchy_sections_string or "top level"
  560. message.append('Extra %s, %s in the section: %s' % (section_or_value, name, section_string))
  561. if message:
  562. error = {
  563. 'name': 'ini configuration',
  564. 'message': ', '.join(message),
  565. }
  566. error_list.append(error)
  567. def check_config(request):
  568. """Check config and view for the list of errors"""
  569. if not is_admin(request.user):
  570. return HttpResponse(_("You must be a superuser."))
  571. context = {
  572. 'conf_dir': os.path.realpath(os.getenv("HUE_CONF_DIR", get_desktop_root("conf"))),
  573. 'error_list': _get_config_errors(request, cache=False),
  574. }
  575. if request.GET.get('format') == 'json':
  576. return JsonResponse(context)
  577. else:
  578. return render('check_config.mako', request, context, force_template=True)
  579. def check_config_ajax(request):
  580. """Alert administrators about configuration problems."""
  581. if not is_admin(request.user):
  582. return HttpResponse('')
  583. error_list = _get_config_errors(request)
  584. if not error_list:
  585. # Return an empty response, rather than using the mako template, for performance.
  586. return HttpResponse('')
  587. return render('config_alert_dock.mako',
  588. request,
  589. dict(error_list=error_list),
  590. force_template=True)
  591. def get_debug_level(request):
  592. return JsonResponse({'status': 0, 'debug_all': _get_all_debug()})
  593. @require_POST
  594. def set_all_debug(request):
  595. if not is_admin(request.user):
  596. return JsonResponse({'status': 1, 'message': _('You must be a superuser.')})
  597. _set_all_debug()
  598. return JsonResponse({'status': 0, 'debug_all': True})
  599. @require_POST
  600. def reset_all_debug(request):
  601. if not is_admin(request.user):
  602. return JsonResponse({'status': 1, 'message': _('You must be a superuser.')})
  603. _reset_all_debug()
  604. return JsonResponse({'status': 0, 'debug_all': False})
  605. # This is a global non-view for inline KO i18n
  606. def _ko(str=""):
  607. return _(str).replace("'", "\\'")
  608. # This global Mako filtering option, use it with ${ yourvalue | n,antixss }
  609. def antixss(value):
  610. xss_regex = re.compile(r'<[^>]+>')
  611. return xss_regex.sub('', value)