views.py 15 KB

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