views.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 os
  20. import sys
  21. import tempfile
  22. import time
  23. import traceback
  24. import zipfile
  25. from django.conf import settings
  26. from django.shortcuts import render_to_response
  27. from django.http import HttpResponse
  28. from django.core.urlresolvers import reverse
  29. from django.core.servers.basehttp import FileWrapper
  30. from django.shortcuts import redirect
  31. from django.utils.translation import ugettext as _
  32. import django.views.debug
  33. import desktop.conf
  34. import desktop.log.log_buffer
  35. from desktop.api import massaged_tags_for_json, massaged_documents_for_json,\
  36. _get_docs
  37. from desktop.lib import django_mako
  38. from desktop.lib.conf import GLOBAL_CONFIG
  39. from desktop.lib.django_util import login_notrequired, render_json, render
  40. from desktop.lib.i18n import smart_str
  41. from desktop.lib.paths import get_desktop_root
  42. from desktop.log.access import access_log_level, access_warn
  43. from desktop.models import UserPreferences, Settings
  44. from desktop import appmanager
  45. LOG = logging.getLogger(__name__)
  46. def home(request):
  47. docs = _get_docs(request.user)
  48. apps = appmanager.get_apps_dict(request.user)
  49. return render('home.mako', request, {
  50. 'apps': apps,
  51. 'json_documents': json.dumps(massaged_documents_for_json(docs, request.user)),
  52. 'json_tags': json.dumps(massaged_tags_for_json(docs, request.user)),
  53. 'tours_and_tutorials': Settings.get_settings().tours_and_tutorials
  54. })
  55. @access_log_level(logging.WARN)
  56. def log_view(request):
  57. """
  58. We have a log handler that retains the last X characters of log messages.
  59. If it is attached to the root logger, this view will display that history,
  60. otherwise it will report that it can't be found.
  61. """
  62. if not request.user.is_superuser:
  63. return HttpResponse(_("You must be a superuser."))
  64. l = logging.getLogger()
  65. for h in l.handlers:
  66. if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
  67. return render('logs.mako', request, dict(log=[l for l in h.buf], query=request.GET.get("q", "")))
  68. return render('logs.mako', request, dict(log=[_("No logs found!")]))
  69. @access_log_level(logging.WARN)
  70. def download_log_view(request):
  71. """
  72. Zip up the log buffer and then return as a file attachment.
  73. """
  74. if not request.user.is_superuser:
  75. return HttpResponse(_("You must be a superuser."))
  76. l = logging.getLogger()
  77. for h in l.handlers:
  78. if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
  79. try:
  80. # We want to avoid doing a '\n'.join of the entire log in memory
  81. # in case it is rather big. So we write it to a file line by line
  82. # and pass that file to zipfile, which might follow a more efficient path.
  83. tmp = tempfile.NamedTemporaryFile()
  84. log_tmp = tempfile.NamedTemporaryFile("w+t")
  85. for l in h.buf:
  86. log_tmp.write(smart_str(l) + '\n')
  87. # This is not just for show - w/out flush, we often get truncated logs
  88. log_tmp.flush()
  89. t = time.time()
  90. zip = zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED)
  91. zip.write(log_tmp.name, "hue-logs/hue-%s.log" % t)
  92. zip.close()
  93. length = tmp.tell()
  94. # if we don't seek to start of file, no bytes will be written
  95. tmp.seek(0)
  96. wrapper = FileWrapper(tmp)
  97. response = HttpResponse(wrapper, content_type="application/zip")
  98. response['Content-Disposition'] = 'attachment; filename=hue-logs-%s.zip' % t
  99. response['Content-Length'] = length
  100. return response
  101. except Exception, e:
  102. logging.exception("Couldn't construct zip file to write logs to: %s") % e
  103. return log_view(request)
  104. return render_to_response("logs.mako", dict(log=[_("No logs found.")]))
  105. @access_log_level(logging.DEBUG)
  106. def prefs(request, key=None):
  107. """Get or set preferences."""
  108. if key is None:
  109. d = dict( (x.key, x.value) for x in UserPreferences.objects.filter(user=request.user))
  110. return render_json(d)
  111. else:
  112. if "set" in request.REQUEST:
  113. try:
  114. x = UserPreferences.objects.get(user=request.user, key=key)
  115. except UserPreferences.DoesNotExist:
  116. x = UserPreferences(user=request.user, key=key)
  117. x.value = request.REQUEST["set"]
  118. x.save()
  119. return render_json(True)
  120. if "delete" in request.REQUEST:
  121. try:
  122. x = UserPreferences.objects.get(user=request.user, key=key)
  123. x.delete()
  124. return render_json(True)
  125. except UserPreferences.DoesNotExist:
  126. return render_json(False)
  127. else:
  128. try:
  129. x = UserPreferences.objects.get(user=request.user, key=key)
  130. return render_json(x.value)
  131. except UserPreferences.DoesNotExist:
  132. return render_json(None)
  133. def bootstrap(request):
  134. """Concatenates bootstrap.js files from all installed Hue apps."""
  135. # Has some None's for apps that don't have bootsraps.
  136. all_bootstraps = [ (app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name) ]
  137. # Iterator over the streams.
  138. concatenated = [ "\n/* %s */\n%s" % (app.name, b.read()) for app, b in all_bootstraps if b is not None ]
  139. # HttpResponse can take an iteratable as the first argument, which
  140. # is what happens here.
  141. return HttpResponse(concatenated, mimetype='text/javascript')
  142. _status_bar_views = []
  143. def register_status_bar_view(view):
  144. global _status_bar_views
  145. _status_bar_views.append(view)
  146. @access_log_level(logging.DEBUG)
  147. def status_bar(request):
  148. """
  149. Concatenates multiple views together to build up a "status bar"/"status_bar".
  150. These views are registered using register_status_bar_view above.
  151. """
  152. resp = ""
  153. for view in _status_bar_views:
  154. try:
  155. r = view(request)
  156. if r.status_code == 200:
  157. resp += r.content
  158. else:
  159. LOG.warning("Failed to execute status_bar view %s" % (view,))
  160. except:
  161. LOG.exception("Failed to execute status_bar view %s" % (view,))
  162. return HttpResponse(resp)
  163. def dump_config(request):
  164. # Note that this requires login (as do most apps).
  165. show_private = False
  166. conf_dir = os.path.realpath(os.getenv("HUE_CONF_DIR", get_desktop_root("conf")))
  167. if not request.user.is_superuser:
  168. return HttpResponse(_("You must be a superuser."))
  169. if request.GET.get("private"):
  170. show_private = True
  171. apps = sorted(appmanager.DESKTOP_MODULES, key=lambda app: app.name)
  172. apps_names = [app.name for app in apps]
  173. top_level = sorted(GLOBAL_CONFIG.get().values(), key=lambda obj: apps_names.index(obj.config.key))
  174. return render("dump_config.mako", request, dict(
  175. show_private=show_private,
  176. top_level=top_level,
  177. conf_dir=conf_dir,
  178. apps=apps))
  179. if sys.version_info[0:2] <= (2,4):
  180. def _threads():
  181. import threadframe
  182. return threadframe.dict().iteritems()
  183. else:
  184. def _threads():
  185. return sys._current_frames().iteritems()
  186. @access_log_level(logging.WARN)
  187. def threads(request):
  188. """Dumps out server threads. Useful for debugging."""
  189. if not request.user.is_superuser:
  190. return HttpResponse(_("You must be a superuser."))
  191. out = []
  192. for thread_id, stack in _threads():
  193. out.append("Thread id: %s" % thread_id)
  194. for filename, lineno, name, line in traceback.extract_stack(stack):
  195. out.append(" %-20s %s(%d)" % (name, filename, lineno))
  196. out.append(" %-80s" % (line))
  197. out.append("")
  198. return HttpResponse("\n".join(out), content_type="text/plain")
  199. @access_log_level(logging.WARN)
  200. def memory(request):
  201. """Dumps out server threads. Useful for debugging."""
  202. if not request.user.is_superuser:
  203. return HttpResponse(_("You must be a superuser."))
  204. heap = settings.MEMORY_PROFILER.heap()
  205. heap = heap[int(request.GET.get('from', 0)):int(request.GET.get('to', len(heap)))]
  206. if 'index' in request.GET:
  207. heap = heap[int(request.GET['index'])]
  208. if 'type' in request.GET:
  209. heap = getattr(heap, request.GET['type'])
  210. return HttpResponse(str(heap), content_type="text/plain")
  211. def jasmine(request):
  212. return render('jasmine.mako', request, None)
  213. @login_notrequired
  214. def unsupported(request):
  215. return render('unsupported.mako', request, None)
  216. def index(request):
  217. if request.user.is_superuser and request.COOKIES.get('hueLandingPage') != 'home':
  218. return redirect(reverse('about:index'))
  219. else:
  220. return home(request)
  221. def serve_404_error(request, *args, **kwargs):
  222. """Registered handler for 404. We just return a simple error"""
  223. access_warn(request, "404 not found")
  224. return render("404.mako", request, dict(uri=request.build_absolute_uri()), status=404)
  225. def serve_500_error(request, *args, **kwargs):
  226. """Registered handler for 500. We use the debug view to make debugging easier."""
  227. try:
  228. exc_info = sys.exc_info()
  229. if exc_info:
  230. if desktop.conf.HTTP_500_DEBUG_MODE.get() and exc_info[0] and exc_info[1]:
  231. # If (None, None, None), default server error describing why this failed.
  232. return django.views.debug.technical_500_response(request, *exc_info)
  233. else:
  234. # Could have an empty traceback
  235. return render("500.mako", request, {'traceback': traceback.extract_tb(exc_info[2])})
  236. else:
  237. # exc_info could be empty
  238. return render("500.mako", request, {})
  239. finally:
  240. # Fallback to default 500 response if ours fails
  241. # Will end up here:
  242. # - Middleware or authentication backends problems
  243. # - Certain missing imports
  244. # - Packaging and install issues
  245. pass
  246. _LOG_LEVELS = {
  247. "critical": logging.CRITICAL,
  248. "error": logging.ERROR,
  249. "warning": logging.WARNING,
  250. "info": logging.INFO,
  251. "debug": logging.DEBUG
  252. }
  253. _MAX_LOG_FRONTEND_EVENT_LENGTH = 1024
  254. _LOG_FRONTEND_LOGGER = logging.getLogger("desktop.views.log_frontend_event")
  255. @login_notrequired
  256. def log_frontend_event(request):
  257. """
  258. Logs arguments to server's log. Returns an
  259. empty string.
  260. Parameters (specified via either GET or POST) are
  261. "logname", "level" (one of "debug", "info", "warning",
  262. "error", or "critical"), and "message".
  263. """
  264. def get(param, default=None):
  265. return request.REQUEST.get(param, default)
  266. level = _LOG_LEVELS.get(get("level"), logging.INFO)
  267. msg = "Untrusted log event from user %s: %s" % (
  268. request.user,
  269. get("message", "")[:_MAX_LOG_FRONTEND_EVENT_LENGTH])
  270. _LOG_FRONTEND_LOGGER.log(level, msg)
  271. return HttpResponse("")
  272. def who_am_i(request):
  273. """
  274. Returns username and FS username, and optionally sleeps.
  275. """
  276. try:
  277. sleep = float(request.REQUEST.get("sleep") or 0.0)
  278. except ValueError:
  279. sleep = 0.0
  280. time.sleep(sleep)
  281. return HttpResponse(request.user.username + "\t" + request.fs.user + "\n")
  282. def commonheader(title, section, user, padding="90px"):
  283. """
  284. Returns the rendered common header
  285. """
  286. current_app = None
  287. other_apps = []
  288. if user.is_authenticated():
  289. apps = appmanager.get_apps(user)
  290. apps_list = appmanager.get_apps_dict(user)
  291. for app in apps:
  292. if app.display_name not in [
  293. 'beeswax', 'impala', 'pig', 'jobsub', 'jobbrowser', 'metastore', 'hbase', 'sqoop', 'oozie', 'filebrowser',
  294. 'useradmin', 'search', 'help', 'about', 'zookeeper', 'proxy', 'rdbms', 'spark']:
  295. other_apps.append(app)
  296. if section == app.display_name:
  297. current_app = app
  298. else:
  299. apps_list = []
  300. return django_mako.render_to_string("common_header.mako", {
  301. 'current_app': current_app,
  302. 'apps': apps_list,
  303. 'other_apps': other_apps,
  304. 'title': title,
  305. 'section': section,
  306. 'padding': padding,
  307. 'user': user,
  308. 'is_demo': desktop.conf.DEMO_ENABLED.get()
  309. })
  310. def commonfooter(messages=None):
  311. """
  312. Returns the rendered common footer
  313. """
  314. if messages is None:
  315. messages = {}
  316. hue_settings = Settings.get_settings()
  317. return django_mako.render_to_string("common_footer.mako", {
  318. 'messages': messages,
  319. 'version': settings.HUE_DESKTOP_VERSION,
  320. 'collect_usage': collect_usage(),
  321. 'tours_and_tutorials': hue_settings.tours_and_tutorials
  322. })
  323. def collect_usage():
  324. return desktop.conf.COLLECT_USAGE.get() and Settings.get_settings().collect_usage
  325. # If the app's conf.py has a config_validator() method, call it.
  326. CONFIG_VALIDATOR = 'config_validator'
  327. #
  328. # Cache config errors because (1) they mostly don't go away until restart,
  329. # and (2) they can be costly to compute. So don't stress the system just because
  330. # the dock bar wants to refresh every n seconds.
  331. #
  332. # The actual viewing of all errors may choose to disregard the cache.
  333. #
  334. _CONFIG_ERROR_LIST = None
  335. def _get_config_errors(request, cache=True):
  336. """Returns a list of (confvar, err_msg) tuples."""
  337. global _CONFIG_ERROR_LIST
  338. if not cache or _CONFIG_ERROR_LIST is None:
  339. error_list = [ ]
  340. for module in appmanager.DESKTOP_MODULES:
  341. # Get the config_validator() function
  342. try:
  343. validator = getattr(module.conf, CONFIG_VALIDATOR)
  344. except AttributeError:
  345. continue
  346. if not callable(validator):
  347. LOG.warn("Auto config validation: %s.%s is not a function" %
  348. (module.conf.__name__, CONFIG_VALIDATOR))
  349. continue
  350. try:
  351. error_list.extend(validator(request.user))
  352. except Exception, ex:
  353. LOG.exception("Error in config validation by %s: %s" % (module.nice_name, ex))
  354. _CONFIG_ERROR_LIST = error_list
  355. return _CONFIG_ERROR_LIST
  356. def check_config(request):
  357. """Check config and view for the list of errors"""
  358. if not request.user.is_superuser:
  359. return HttpResponse(_("You must be a superuser."))
  360. conf_dir = os.path.realpath(os.getenv("HUE_CONF_DIR", get_desktop_root("conf")))
  361. return render('check_config.mako', request, {
  362. 'error_list': _get_config_errors(request, cache=False),
  363. 'conf_dir': conf_dir
  364. },
  365. force_template=True)
  366. def check_config_ajax(request):
  367. """Alert administrators about configuration problems."""
  368. if not request.user.is_superuser:
  369. return HttpResponse('')
  370. error_list = _get_config_errors(request)
  371. if not error_list:
  372. # Return an empty response, rather than using the mako template, for performance.
  373. return HttpResponse('')
  374. return render('config_alert_dock.mako',
  375. request,
  376. dict(error_list=error_list),
  377. force_template=True)